您可以编写预期会抛出的异步测试吗? [英] Can you write async tests that expect toThrow?

查看:84
本文介绍了您可以编写预期会抛出的异步测试吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()
})

但是开玩笑只是失败了,而不是通过了测试:

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' string will match any part of the error thrown.

这篇关于您可以编写预期会抛出的异步测试吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆