【发布时间】:2020-05-03 10:05:18
【问题描述】:
我有一个类,它有一个名为 init() 的异步构造函数。我正在尝试为它创建一个测试,但我遇到了一些问题。代码工作正常,但测试给出以下错误:
超时 - 在 5000 毫秒超时内未调用异步回调 由 jest.setTimeout.Timeout 指定 - 未调用异步回调 在 jest.setTimeout.Error 指定的 5000 毫秒超时内:
这是课程:
const { Settings } = require("../models/settings");
const moment = require("moment");
class Config {
async init() {
let settings = await Settings.findOne(); // This looks like the line where it gets stuck
if (!settings) settings = await createDefaultConfig();
this.lastBookableDay = settings.lastBookableDay;
this.slotDuration = settings.slotDuration;
this.interval = settings.interval;
this.expireOffset = settings.expireOffset;
this.cancelationNotice = settings.cancelationNotice;
this.week = settings.week;
}
}
async function createDefaultConfig() {
const settings = await Settings.find();
let last = moment().format("YYYY-MM-DD");
last = moment(last).add(10, "day").unix();
if (settings.length < 1) {
const newSettings = new Settings({
lastBookableDay: last,
slotDuration: 50,
interval: 10,
expireOffset: 60,
cancelationNotice: 24,
week: [...new Array(7)].map(() =>
({ startHours: 10, startMinutes: 0, slotNumber: 5, off: false }))
});
await newSettings.save();
}
}
module.exports = Config;
我还有其他可以毫无问题地访问数据库的测试。
这是失败测试的代码(为简单起见,没有清理数据库):
const Settings = require("./settings.js");
describe("Settings class", () => {
it("should init settings instance", async () => {
const settings = new Settings();
await settings.init();
console.log(settings)
expect(settings.slotDuration).toBe(50);
})
});
谁能指出我做错了什么?谢谢。
【问题讨论】:
-
1. jest 的标签是 jestjs 2. 这看起来像 mocha 3. 使用完成的文档状态:mochajs.org/#asynchronous-code
-
不,我的依赖项中甚至没有 mocha。
-
我猜它是全局安装的。玩笑使用
test()命令,搜索js test describe只会产生 mocha 结果。 -
jestjs.io/docs/en/setup-teardown,在“范围”下 -> “您还可以使用描述块将测试组合在一起”。 “它”或“测试”是等价的。从未使用过 mocha,也没有在我的全局安装中使用过,事实上“npm list -g mocha”什么也没返回。
-
没错,我的错。
console.log(settings)的输出是什么?
标签: javascript node.js async-await jestjs