What's the difference between the following two ways of testing async functions expected to throw in Jest?

huangapple go评论61阅读模式
英文:

What's the difference between the following two ways of testing async functions expected to throw in Jest?

问题

Option 1:

await expect(asyncFun()).rejects.toThrowError(errorObj)

Option 2:

await expect(async () => {
  await asyncFun()
}).rejects.toThrowError(errorObj)

Option 1 和 Option 2 之间有什么区别吗?

英文:

Option 1:

await expect(asyncFun()).rejects.toThrowError(errorObj)

Option 2:

await expect(async () => {
  await asyncFun()
}).rejects.toThrowError(errorObj)

Is there a difference between option 1 and option 2?

答案1

得分: 2

是的,存在差异。第二个代码片段<s>根本不起作用</s>没有记录为可用。

与同步的.toThrow()不同,异步测试预期错误不是通过将函数传递给expect()来完成的。.rejects应该用于一个Promise,而不是一个函数(尽管它在获取一个函数时似乎仍然会调用它)。

英文:

Yes, there is a difference. The second snippet <s>simply does not work</s> is not documented to work.

Unlike the synchronous .toThrow(), testing for expected errors asynchronously is not done by passing a function to expect(). .rejects is meant to be used on a promise, not on a function (although it still seems to call it when it gets one).

huangapple
  • 本文由 发表于 2023年5月22日 21:03:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定