Expect.assertions 在 async/await 函数中

Expect.assertions in async/await function

来自 Jest 文档:

Expect.assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

这意味着,如果我们正在测试 拒绝 个案例 promisescatch 中的断言),没有 expect.assertions promise 可能会得到解决,我们的测试 将通过 。然而,我们在测试函数中没有发现任何错误,我们的断言实际上从来没有 运行。换句话说,我们没有检查我们想要的东西。我们得到了答案,但没有回答我们的问题,因为 fulfilledpromise 不会通过测试 。综上所述,在检查 rejections/errors 时定义断言的数量是必须的。

文档中还有一个例子:

test('the data is peanut butter', async () => {
  expect.assertions(1);
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

因为我们使用的是async/await模式,所以我们会等待promise解决,我们的测试条件肯定会运行.

这里expect.assertions的目的是什么?我们真的需要在这段代码中使用 expect.assertions 还是编写它只是一种最佳实践?

你完全正确。

使用 expect.assertions 是必要的 当使用 catch.

测试被拒绝的 Promise 时

在测试已解决的 Promise 或使用 .rejects.

测试被拒绝的 Promise 时,不需要使用 expect.assertions

对于像这样的简单测试,expect.assertions 不是特别有用。对于更复杂的异步测试,有时添加 expect.assertions 作为额外的保护措施以确保测试按预期运行会很有用。