如果您正在等待任何异步函数调用,是否需要使用Expect.assertions()? [英] Necessary to use expect.assertions() if you're awaiting any async function calls?

查看:163
本文介绍了如果您正在等待任何异步函数调用,是否需要使用Expect.assertions()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've found a lot of this sort of thing when refactoring our Jest test suites:

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

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

I believe the expect.assertions(2) line is redundant here, and can safely be removed, because we already await the async call to login().

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

Am I correct, or have I misunderstood how expect.assertions works?

推荐答案

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

expect.assertions is important when testing the error scenarios of asynchronous code, and is not redundant.

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

If you remove expect.assertions from your example you can't be confident that login did in fact throw the error.

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

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

Let's say someone changes the behavior of login to throw an error based on some other logic, or someone has affected the mock for this test which no longer causes login to throw. The assertions in the catch block won't run but the test will still pass.

在测试开始时使用expect.assertions可以确保如果catch内的断言不运行,则会导致失败.

Using expect.assertions at the start of the test ensures that if the assertions inside the catch don't run, we get a failure.

这篇关于如果您正在等待任何异步函数调用,是否需要使用Expect.assertions()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆