我正在使用JEST和Got测试端点。我预计会出现403禁止错误。以下代码从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();
输出:
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并没有捕获到HTTPError时,没有堆栈跟踪,而且我也看不到错误发生的位置。如果还有其他错误,我会确切地看到是哪条测试线造成的。为什么?
答案 0 :(得分:4)
expect(...).toThrow()
用于检查同步功能是否引发了错误。尽管异步函数使用相同的throw
/ catch
术语,但它并未涵盖Promise是否落入拒绝状态的测试。
改为尝试expect(...).rejects.toThrow()
:
expect(() => api(`verify/${profile.auth.verifyToken}`, {method: 'POST'}).json())
.rejects.toThrow();