如何解决开玩笑/表达:仅当存在多个描述块时,测试才会失败并出现Async错误
我的Express后端有一个Jest测试文件,当它包含一个describe()
块时,它可以完美地工作。但是,一旦添加了另一个describe块,无论设置了多长时间,我都会收到此错误:
Timeout - Async callback was not invoked within the 30000ms timeout specified by jest.setTimeout.
如果我将第二个describe块添加到一个单独的文件中,则它们两个都可以很好地运行,并且它们的合并运行时间少于30秒。但是我没有任何理由每次想要新的测试套件时都创建新文件。
这是两个套件的极为简化的版本:
jest.setTimeout(30000);
describe('Mealplan Model Test',() => {
beforeAll(async () => {
await db.Connection;
});
afterAll(async () => {
await mongoose.connection.close();
});
it('create & save mealPlan successfully',async (done) => {
// Test logic
});
// You shouldn't be able to add in any field that isn't defined in the schema
it('insert mealplan successfully,but the extra field does not persist',async (done) => {
// test logic
});
// etc
});
describe('Create User recipes and foods based on admin versions',() => {
let foodAdmin,recipeAdmin,user;
beforeAll(async () => {
await db.Connection;
});
afterAll(async () => {
await mongoose.connection.close();
});
it('creates user recipe based on admin recipe',async () => {
// test logic
});
it('returns the correct userRecipe if one already exists',async () => {
// test logic
});
// etc
});
解决方法
describe
本身不应该影响测试的运行方式,这是因为存在多个afterAll
。 mongoose.connection.close()
关闭连接,但未在beforeAll
中重新打开。
猫鼬将其创建的任何承诺链接到连接承诺,如果连接是 从来没有建立。
如果describe
个组重复使用同一连接,则在顶层仅应关闭一次连接:
beforeAll(async () => {
await db.Connection;
});
afterAll(async () => {
await mongoose.connection.close();
});