javascript - 如何使用 jest 测试嵌套的 promise 函数?
问题描述
我现在拥有的简单代码版本是
const func = (arg1,arg2) =>{
const param1;
return promiseA(arg1).then(data => {
arg2.forEach(element => {
promiseB(param1, element, data).then(output => {
if(output === "null"){
throw PATH_ERROR; // This is the error I want to test, but it does not catch in test
}
console.log(output);
}).catch(e=>{
console.log(e);
return e;
});
});
});
};
我现在拥有的开玩笑的测试代码是:
describe('func function test', () =>{
it('Should throw PATH_ERROR if promiseB cannot find the route', () =>{
expect.assertions(1);
return func(arg1,arg2).catch(e=>{
expect(e).toMatch("PATH_ERROR");
});
});
});
现在,测试将失败,因为实际expect.assersions()
是0
而不是1
. 我认为这是因为.catch()
in jest 正在测试promiseA
函数,因为func
返回了promiseA
,但是错误是由promiseB
.
所以我的问题是:如果这是我的想法,我如何在嵌套的 promise 函数中测试内部的 promise 函数。
我还在学习开玩笑和承诺,如果代码结构不太适合测试或正常开发,请毫不犹豫地指出。非常感谢你在这里帮助我。
解决方案
您需要返回 in 的承诺,promiseB()
并且应该将catch 中promiseA()
的语句更改为.return e
throw e
const func = (arg1,arg2) =>{
const param1;
return promiseA(arg1).then(data => {
const promises = []
arg2.forEach(element => {
const promise = promiseB(param1, element, data).then(output => {
if(output === "null"){
throw PATH_ERROR; // This is the error I want to test, but it does not catch in test
}
console.log(output);
}).catch(e=>{
console.log(e);
throw e;
});
promises.push(promise)
});
return Promise.all(promises);
});
};
推荐阅读
- fluentd - 使用 fluentd http_pull 传递参数和算法
- java - Java if 语句包含字母
- python - Python,带有基本身份验证的 HTTPS GET,然后是基本身份验证后的 Token
- angular - Angular如何在没有usign按钮的情况下显示模态
- mysql - 我如何在nodejs中将img上传到mysql数据库
- python - 从给定名称的excel中导出工作表并将它们保存到新的excel文件中
- tomcat - Tomcat9 STDOUT 文件不断记录 DEBUG 消息
- python - Pandas datetime - 仅将时间保留为 dtype datetime
- python - Streamlit Cache 在昂贵的功能上。避免在计算时重新启动它
- android - 如果画布文本宽度增加,则将 ImageView 移至左侧