![](/img/trans.png)
[英]How to test that an error is re-thrown in a catch statement with Jest
[英]How do I get Jest to catch the thrown error as expected?
我正在嘗試用 Jest 編寫一些測試並不斷得到以下結果。 如何讓 Jest 按預期捕獲拋出的錯誤? 代碼:
test("Test that TEXT_PROPERTIES can throw a typeError", () => {
function testError() {
try {
throw new TypeError(`why doesn't this work`);
} catch (e) {
console.error(e);
}
}
expect(() => {
testError();
}).toThrow();
});
結果:
× Test that TEXT_PROPERTIES can throw a typeError (11 ms)
● Test that TEXT_PROPERTIES can throw a typeError
expect(received).toThrow()
Received function did not throw
62 | expect(() => {
63 | testError();
> 64 | }).toThrow();
| ^
65 | });
66 |
at Object.<anonymous> (tests/components/typography/typography.test.js:64:6)
console.error
TypeError: why doesn't this work
我已經閱讀了這個問題的許多其他“答案”,但沒有一個有效。
testError
不會因為 try-catch 塊而向外界拋出錯誤。 從 Jest 的期望來看, testError
返回 undefined 而不是異常(錯誤)。 這是一個類似的測試:
function testError() { try { throw new TypeError(`why doesn't this work`); } catch (e) { console.error(e); } } var result = testError(); console.log(result); // undefined console.log(result instanceof TypeError); // false
將 function 更改為:
function testError() {
throw new TypeError(`why doesn't this work`);
}
function testError() { throw new TypeError(`why doesn't this work`); } // We want to use try-catch to encapsulate the error try { result(); } catch (e){ console.log(e); // undefined console.log(e instanceof TypeError); // false console.log(e instanceof TypeError); // false }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.