如果您正在等待任何异步函数调用,是否需要使用Expect.assertions()?

cal*_*lum 6 jestjs

重构Jest测试套件时,我发现了很多这样的东西:

it('calls the API and throws an error', async () => {
  expect.assertions(2);
  try {
    await login('email', 'password');
  } catch (error) {
    expect(error.name).toEqual('Unauthorized');
    expect(error.status).toEqual(401);
  }
});
Run Code Online (Sandbox Code Playgroud)

我相信这expect.assertions(2)行是多余的,可以放心删除,因为我们已经await异步调用了login()

我是正确的,还是我误解了expect.assertions工作原理?

use*_*257 17

expect.assertions 在测试异步代码的错误方案时很重要,并且不是多余的。

如果expect.assertions从示例中删除,您将无法确定login确实引发了错误。

it('calls the API and throws an error', async () => {
  try {
    await login('email', 'password');
  } catch (error) {
    expect(error.name).toEqual('Unauthorized');
    expect(error.status).toEqual(401);
  }
});
Run Code Online (Sandbox Code Playgroud)

假设有人login基于其他逻辑更改了抛出错误的行为,或者某人影响了该测试的模拟,而该模拟不再导致login抛出错误。块中的断言catch不会运行,但测试仍会通过。

使用expect.assertions在测试保证的开始,如果抓里面的断言不跑,我们得到了一个失败。

  • 因此,如果在这种情况下,测试代码在“login”之后有类似“fail”的内容,则不需要“expect.assertions”? (2认同)

dan*_*y74 11

我认为我们在这里忽略了显而易见的事情。

Expect.assertions(3) 只是说......

我预计在测试超时之前会调用 3 个期望语句。例如

expect(actual1).toEqual(expected1);
expect(actual2).toEqual(expected2);
expect(actual3).toEqual(expected3);
Run Code Online (Sandbox Code Playgroud)

这种超时业务就是使用expect.assertions的原因。在纯同步测试中使用它是愚蠢的。至少可以在规范文件内的订阅块(或其他异步块)中找到期望语句之一。


Moy*_*ote 9

这是来自 Jest 文档:

Expect.assertions(number) 验证在测试期间调用了一定数量的断言。这在测试异步代码时通常很有用,以确保回调中的断言确实被调用。

换句话说,expect.assertions确保在测试结束时做出 n 个断言

特别是在编写新测试时使用它是很好的,因此可以轻松检查在测试期间是否做出了正确的断言。异步测试通常会通过,因为在测试运行程序(Jest、Mocha 等)认为测试完成之前没有做出预期的断言。