JEST Received 函数没有抛出,但是抛出了 HTTPError [英] JEST Received function did not throw, but HTTPError is thrown
问题描述
我正在使用 JEST 和 Got 测试端点.我预计会出现 403 Forbidden 错误.下面的代码从 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:devmezinamiridiciinfrastructure
ode_modulesgotdistsourceas-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 被抛出但未被捕获时,没有堆栈跟踪,我看不到错误在哪里抛出.如果还有其他错误,我会确切地看到哪个测试线是负责的.为什么?
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()
用于检查函数调用是否抛出错误.调用异步函数时,它永远不会抛出错误;相反,它返回一个 Promise
,它可能最终被拒绝".尽管异步函数使用相同的 throw
/catch
术语,但检测抛出错误所需的代码与检测被拒绝 Promise 所需的代码不同.这就是 Jest 需要不同断言技术的原因.
expect(...).toThrow()
is for checking if an error is thrown from a function call. When calling an async function, it never throws an error; rather it returns a Promise
which may eventually become "rejected." Although async functions use the same throw
/catch
terminology, the code required to detect a thrown error differs from what's required to detect a rejected Promise. This is why Jest needs a different assertion technique.
尝试 expect(...).rejects.toThrow()
代替:
Try expect(...).rejects.toThrow()
instead:
await expect(() => api(`verify/${profile.auth.verifyToken}`, {method: 'POST'}).json())
.rejects.toThrow();
注意你必须await
这个断言,因为Jest需要等到Promise
完成后才能看到它是解决了还是拒绝了.
Notice you have to await
this assertion because Jest needs to wait until the Promise
finalizes before seeing whether it resolved or rejected.
这篇关于JEST Received 函数没有抛出,但是抛出了 HTTPError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!