[英]How to test a nested promise function using jest?
我现在拥有的简单代码版本是
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()
正在测试promiseA
function,因为func
返回promiseA
,但是错误是由promiseB
抛出的。
所以我的问题是:如果这是我的想法,我该如何在嵌套的 promise ZC1C425274ZA9DEF14AB408D9D9DEEBZ function 中测试内部 promise function。
我还在学习jest和promise,如果代码结构不太适合测试或正常开发,请毫不犹豫地指出。 非常感谢你在这里帮助我。
您需要在promiseB()
中返回promiseA()
() 的承诺,并且应该将 catch 中的语句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);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.