首页 > 解决方案 > 如何使用 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 函数。

我还在学习开玩笑和承诺,如果代码结构不太适合测试或正常开发,请毫不犹豫地指出。非常感谢你在这里帮助我。

标签: javascriptnode.jsasynchronouspromisejestjs

解决方案


您需要返回 in 的承诺,promiseB()并且应该将catch 中promiseA()的语句更改为.return ethrow 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);
    });
};

推荐阅读