你能编写期望 toThrow 的异步测试吗? [英] Can you write async tests that expect toThrow?
本文介绍了你能编写期望 toThrow 的异步测试吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个异步测试,期望异步函数像这样抛出:
I'm writing an async test that expects the async function to throw like this:
it("expects to have failed", async () => {
let getBadResults = async () => {
await failingAsyncTest()
}
expect(await getBadResults()).toThrow()
})
但是 jest 只是失败而不是通过测试:
But jest is just failing instead of passing the test:
FAIL src/failing-test.spec.js
● expects to have failed
Failed: I should fail!
如果我将测试重写为如下所示:
If I rewrite the test to looks like this:
expect(async () => {
await failingAsyncTest()
}).toThrow()
我收到此错误而不是通过测试:
I get this error instead of a passing test:
expect(function).toThrow(undefined)
Expected the function to throw an error.
But it didn't throw anything.
推荐答案
你可以像这样测试你的异步函数:
You can test your async function like this:
it('should test async errors', async () => {
await expect(failingAsyncTest())
.rejects
.toThrow('I should fail');
});
'I should fail' 字符串将匹配抛出的错误的任何部分.
'I should fail' string will match any part of the error thrown.
这篇关于你能编写期望 toThrow 的异步测试吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文