问题描述
在重构我们的 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)
行在这里是多余的,可以安全地删除,因为我们已经 await
对 login()
.
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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!