小编典典

你能写出期望抛出的异步测试吗?

all

我正在编写一个异步测试,期望异步函数像这样抛出:

it("expects to have failed", async () => {
  let getBadResults = async () => {
    await failingAsyncTest()
  }
  expect(await getBadResults()).toThrow()
})

但是 jest 只是失败了,而不是通过了测试:

 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.

阅读 64

收藏
2022-05-10

共1个答案

小编典典

您可以像这样测试您的异步功能:

it('should test async errors', async () =>  {        
    await expect(failingAsyncTest())
    .rejects
    .toThrow('I should fail');
});

‘I should fail’ 字符串将匹配所抛出错误的任何部分。

2022-05-10