我正在使用 JEST 和 Got 测试端点。我预计 403 禁止错误。以下代码打印来自 catch block 的错误并且失败,相同的调用不会引发错误。为什么?
try {
response = await api(`verify/${profile.auth.verifyToken}`, {method: 'POST'}).json();
} catch (e) {
console.log(e);
}
expect(async () => {
response = await api(`verify/${profile.auth.verifyToken}`, {method: 'POST'}).json();
}).toThrow();
输出:
console.log test/api.int.test.js:112
HTTPError: Response code 403 (Forbidden)
at EventEmitter.<anonymous> (C:\dev\mezinamiridici\infrastructure\node_modules\got\dist\source\as-promise.js:118:31)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
name: 'HTTPError'
}
Error: expect(received).toThrow()
Received function did not throw
此变体也不起作用:
expect(() => api(`verify/${profile.auth.verifyToken}`, {method: 'POST'})).toThrow();
顺便说一句,当 HTTPError 被抛出但未被捕获时,没有堆栈跟踪,我看不到错误被抛出的位置。如果还有其他错误,我会确切地看到哪条测试线负责。为什么?
最佳答案
expect(...).toThrow()
用于检查函数调用是否引发错误。调用异步函数时,它永远不会抛出错误;而是返回 Promise
最终可能会被“拒绝”。虽然异步函数使用相同的 throw
/catch
术语,检测抛出的错误所需的代码与检测拒绝的 Promise 所需的代码不同。这就是为什么 Jest 需要一种不同的断言技术。
试试 expect(...).rejects.toThrow()
反而:
await expect(() => api(`verify/${profile.auth.verifyToken}`, {method: 'POST'}).json())
.rejects.toThrow();
请注意,您必须 await
这个断言是因为 Jest 需要等到 Promise
在查看它是解决还是拒绝之前完成。
关于javascript - JEST Received 函数没有抛出,但是抛出了 HTTPError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61214473/