【发布时间】:2020-12-30 20:47:41
【问题描述】:
如果出现错误,我如何在 Jest 中测试我的 try / catch 块,我确定 catch 会处理?例如,我想测试此代码以从单独的文件中读取令牌。我想测试我的捕获,但问题是我不知道如何在 Jest 中创建一个情况以在 Jest 中处理错误。
const readToken = async () => {
try{
const readFile = await fs.readFile('./apiData.json');
const data = JSON.parse(readFile);
return data.token;
}catch(err){
throw err;
}
}
这是我的 Jest 代码,但我认为它不能正常工作,因为在覆盖范围内向我展示了带有 catch(err) 的行未被发现。
it('should return catch error',async (done) => {
try{
await readToken()
done()
}catch(e){
done(e);
}
})
【问题讨论】:
-
jestjs.io/docs/en/expect.html#tothrowerror?而你的捕获是完全没有意义的。
-
}catch(err){ throw err; }是无操作的,一开始就不应该存在。 -
那么你能告诉我更多我应该如何处理这个函数中的错误吗?
-
您需要的方式。除了你,没有人可以决定。如果您需要它像当前一样抛出错误,请删除 try..catch。
-
所以你想说在这个函数中没有必要写 try 和 catch 吗?非常感谢您的回答。
标签: javascript node.js jestjs try-catch supertest