【问题标题】:Jest/Express: Tests fail with Async error only when there are multiple describe blocksJest/Express:仅当有多个描述块时,测试才会失败并出现异步错误
【发布时间】:2020-12-11 16:40:57
【问题描述】:

我的 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
});

【问题讨论】:

  • @Anthony 通读后,我不这么认为。在我的情况下,两个测试套件都在它们自己的情况下成功通过,所以即使失败了,测试也不会继续运行。我想要的是能够在一个测试文件中包含多个描述块并让它们都工作。如果一个失败让另一个运行也没关系。
  • 如果你从 it 块中的参数中删除 done,你能看到会发生什么吗?

标签: javascript express mongoose jestjs


【解决方案1】:

describe 本身不应该影响测试的运行方式,这是因为有多个afterAllmongoose.connection.close() 会关闭连接,但不会在 beforeAll 中重新打开。

Mongoose 为它创建的任何 Promise 链接连接 Promise,如果连接是 从未建立。

如果describe 组重用同一个连接,一个连接应该只在顶层关闭一次:

  beforeAll(async () => {
    await db.Connection;
  });

  afterAll(async () => {
    await mongoose.connection.close();
  });

【讨论】:

  • 所以我们应该只在第一个描述块的文件开头有一个await db.Connection,在文件的末尾有一个await mongoose.connection.close();
  • 你可以省略顶层描述,它在 Jest 中是可选的。它们可以在顶部,前*和后*块的位置无关紧要,只有相似块的顺序。
  • 知道了,问题是我无法合并 beforeAll 和 afterAll 因为我确实在每个描述块中发生了特定于该组测试用例的其他数据库操作。但是你是说我可以有两个 beforeAll 和 afterAll 只要它们的顺序正确?
猜你喜欢
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2023-03-08
相关资源
最近更新 更多