我正在编写一个异步测试,希望异步函数像这样抛出:
it("expects to have failed", async () => {
let getBadResults = async () => {
await failingAsyncTest()
}
expect(await getBadResults()).toThrow()
})
但是,开玩笑只是失败而不是通过测试:
FAIL src/failing-test.spec.js
● expects to have failed
Failed: I should fail!
如果我重写测试看起来像这样:
expect(async () => {
await failingAsyncTest()
}).toThrow()
我收到此错误而不是通过测试:
expect(function).toThrow(undefined)
Expected the function to throw an error.
But it didn't throw anything.
答案 0 :(得分:47)
您可以像这样测试异步功能:
it('should test async errors', async () => {
await expect(failingAsyncTest())
.rejects
.toThrow('I should fail');
});
'我应该失败'字符串将匹配抛出的错误的任何部分。
答案 1 :(得分:2)
我想补充一点,说您正在测试的函数必须抛出一个实际的Error对象throw new Error(...)
。 Jest似乎无法识别您是否仅抛出throw 'An error occurred!'
之类的表达式。