我的Express后端有一个Jest测试文件,当它包含一个describe()
块时,它可以完美地工作。然而,一旦添加了另一个描述块,无论我设置了多长时间的超时,我都会收到这个错误:
Timeout - Async callback was not invoked within the 30000ms timeout specified by jest.setTimeout.
如果我将第二个描述块添加到一个单独的文件中,它们都运行得很好,并且它们的组合运行时间不到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
中重新打开。
Mongoose为它创建的任何promise链接连接promise,如果连接从未建立。
如果describe
组重复使用同一个连接,则应在顶层仅关闭一次连接:
beforeAll(async () => {
await db.Connection;
});
afterAll(async () => {
await mongoose.connection.close();
});