英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论