【发布时间】:2022-03-29 05:11:41
【问题描述】:
我正在尝试为简单的 try-catch 结构函数编写单元测试。我的函数在index.js,测试在check.test.js。我不确定是什么导致了这个问题。
index.js 内部:
// index.js
const UNDEFINED_ERROR = "Undefined detected.";
testFn = () => {
try{
throw new Error(UNDEFINED_ERROR);
}catch(e){
console.log(e);
}
};
module.exports = {
testFn,
UNDEFINED_ERROR
}
check.test.js 内部:
//check.test.js
const {testFn, UNDEFINED_ERROR} = require('./src/index');
describe('test', ()=>{
it('show throw',()=>{
expect(()=>{
testFn();
}).toThrow();
});
});
npm test之后,测试会失败,终端会返回Received function did not throw。
我引用了这个similar question,在函数中删除try-catch后它会完美运行并通过,这只是
// passed version
const UNDEFINED_ERROR = "Undefined detected.";
testFn = () => {
throw new Error(UNDEFINED_ERROR);
};
module.exports = {
testFn,
UNDEFINED_ERROR
}
我是 JS 和 Jest 的新手,非常感谢这里的任何帮助!
【问题讨论】:
-
您的错误已在 try catch 块中捕获,您不应期望
testFn抛出错误,除非在catch块中重新抛出。你可以断言console.log应该用Error调用 -
感谢您的指出! @Teneff 刚刚通过测试我的
console.log()解决了这个问题。真的很感激!
标签: javascript unit-testing jestjs