这是我的错误代码:
FAIL build/__test__/FuncOps.CheckFunctionExistenceByString.test.js
●
expect(CheckFunctionExistenceByStr(
'any string', 'FunctionThatDoesNotExistsInString'
)).toThrow();
Function FunctionThatDoesNotExistsInString does not exists in string.
at CheckFunctionExistenceByStr (build/FuncOps.js:35:15)
at Object.<anonymous> (build/__test__/FuncOps.CheckFunctionExistenceByString.test.js:12:51)
at new Promise (<anonymous>)
at <anonymous>
如您所见,错误确实发生了:Function FunctionThatDoesNotExistsInString does not exists in string.
。然而,它不会被 Jest 捕获为通行证。
这是我的代码:
test(`
expect(CheckFunctionExistenceByStr(
'any string', 'FunctionThatDoesNotExistsInString'
)).toThrow();
`, () => {
expect(CheckFunctionExistenceByStr(
'any string', 'FunctionThatDoesNotExistsInString'
)).toThrow();
}
);
最佳答案
expect(fn).toThrow()
需要一个 fn
函数,调用时 会抛出异常。
但是您正在立即调用 CheckFunctionExistenceByStr
,这会导致函数在运行断言之前抛出异常。
替换
test(`
expect(CheckFunctionExistenceByStr(
'any string', 'FunctionThatDoesNotExistsInString'
)).toThrow();
`, () => {
expect(CheckFunctionExistenceByStr(
'any string', 'FunctionThatDoesNotExistsInString'
)).toThrow();
}
);
与
test(`
expect(() => {
CheckFunctionExistenceByStr(
'any string', 'FunctionThatDoesNotExistsInString'
)
}).toThrow();
`, () => {
expect(() => {
CheckFunctionExistenceByStr(
'any string', 'FunctionThatDoesNotExistsInString'
)
}).toThrow();
}
);
关于javascript - 抛出错误但 Jest 的 `toThrow()` 没有捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47397208/