如果您正在等待任何异步函数调用,是否需要使用Expect.assertions()? [英] Necessary to use expect.assertions() if you're awaiting any async function calls?
问题描述
在重构我们的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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!