JEST接收到的函数未抛出,但抛出了HTTPError [英] JEST Received function did not throw, but HTTPError is thrown
问题描述
我正在使用JEST和Got测试端点.我预计会出现403禁止错误.以下代码从catch块中打印错误,并且失败,即相同的调用未引发错误.为什么?
I am testing an endpoint with JEST and Got. I expect 403 Forbidden error. The following code prints the error from catch block AND fails that the identical call does not throw an error. Why?
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时,就没有堆栈跟踪,而且我也看不到在哪里抛出了错误.如果还有其他错误,我会确切地看到是哪条测试线造成的.为什么?
Btw when the HTTPError is thrown and not catched, there is no stacktrace and I do not see where the error was thrown. If there are other error I exactly see which test line was responsible. Why?
推荐答案
expect(...).toThrow()
用于检查是否从同步函数中引发了错误.尽管异步函数使用相同的throw
/catch
术语,但它并未涵盖对Promise是否陷入拒绝状态的测试.
expect(...).toThrow()
is for checking if an error is thrown from a synchronous function. It does not cover testing if a Promise falls into a rejected state, despite the fact that async functions use the same throw
/catch
terminology.
尝试 expect(...).rejects.toThrow()
代替:
await expect(() => api(`verify/${profile.auth.verifyToken}`, {method: 'POST'}).json())
.rejects.toThrow();
这篇关于JEST接收到的函数未抛出,但抛出了HTTPError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!