javascript - 如何测试 try/catch 内部使用效果?
问题描述
所以我有这个
useEffect(() => {
try {
if (prop1 && prop2) {
callThisFunction()
} else {
callThatFunction()
}
} catch (error) {
console.log(error, 'the err:')
setError(true)
}
}, [])
我想进入 catch 块来断言一些东西,我该怎么做?
目前我已经尝试模拟其中一个callThis/That
函数的实现并抛出错误以使其进入 catch 但这并没有奏效
更新:也试过这个:
callThisFunction.mockImplementation(() => {
throw Error(error)
})
我已经到了它跳入 else 的点,但是由于某种原因,当 else 失败时它不会跳入 catch 中。但代码有效。只是不能得到测试:/
有任何想法吗?
解决方案
您可以使用异步功能:
useEffect(() => {
(async function() {
try {
if (prop1 && prop2) {
callThisFunction()
} else {
callThatFunction()
}
} catch (error) {
console.log(error, 'the err:')
setError(true)
}
})();
}, [])