I am attempting to write some tests in Jest and keep getting the below result. How do I get Jest to catch the thrown error as expected? Code:
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();
});
Result:
× 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
I have read a bunch of other "answers" to this question but none of them work.
testError
does not throw an error to the outside world because of try-catch block. From the perspective of Jest's expect, testError
returns undefined and not an exception (error). Here's a similar test:
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
Change the function to this:
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 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.