[英]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.