gpt4 book ai didi

asynchronous - 异步/等待函数中的 Expect.assertions

转载 作者:行者123 更新时间:2023-12-04 01:13:55 33 4
gpt4 key购买 nike

来自 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.



这意味着,如果我们正在测试 promises 的拒绝案例(在 catch 中的断言),没有 expect.assertions promise可能会解决,我们的测试将通过。然而,我们在测试函数中没有发现任何错误,而且我们的断言实际上从未运行过。换句话说,我们没有检查我们想要什么。我们得到了答案,但不是我们的问题,原因 已完成 promise不会通过测试 .总而言之,在检查拒绝/错误时定义断言的数量是必须的。

文档中有另一个例子:
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 时是必要的.

使用 expect.assertions在测试已解决的 Promise 或使用 .rejects 测试被拒绝的 Promise 时不需要.

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

关于asynchronous - 异步/等待函数中的 Expect.assertions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54706481/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com