如何让 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
我已经阅读了很多关于这个问题的其他“答案”,但 none 其中有效。
testError
不会因为 try-catch 块而向外界抛出错误。从 Jest 的 expect 来看,testError
returns undefined 而不是异常(error)。这是一个类似的测试:
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 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
}
我正在尝试用 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
我已经阅读了很多关于这个问题的其他“答案”,但 none 其中有效。
testError
不会因为 try-catch 块而向外界抛出错误。从 Jest 的 expect 来看,testError
returns undefined 而不是异常(error)。这是一个类似的测试:
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 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
}