Leo*_*rak 11 javascript jestjs gotjs
我正在使用 JEST 和 Got 测试端点。我预计会出现 403 Forbidden 错误。下面的代码从 catch 块打印错误并且失败,相同的调用没有抛出错误。为什么?
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();
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
此变体也不起作用:
expect(() => api(`verify/${profile.auth.verifyToken}`, {method: 'POST'})).toThrow();
Run Code Online (Sandbox Code Playgroud)
顺便说一句,当 HTTPError 被抛出但未被捕获时,没有堆栈跟踪,我看不到错误在哪里抛出。如果还有其他错误,我会确切地看到哪个测试线是负责的。为什么?
Jac*_*cob 25
expect(...).toThrow()用于检查是否从同步函数抛出错误。尽管异步函数使用相同的throw/catch术语,但它不包括测试 Promise 是否陷入拒绝状态。
试试吧expect(...).rejects.toThrow():
await expect(() => api(`verify/${profile.auth.verifyToken}`, {method: 'POST'}).json())
.rejects.toThrow();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4188 次 |
| 最近记录: |