如何使用Jest测试嵌套的Promise函数?

时间:2020-06-28 22:27:52

标签: javascript node.js asynchronous promise jestjs

我现在拥有的简单代码是

td_keys = Literal(Td.keys())
def hello_Td(key: td_keys, td: Td):
    return 'Hello ' + td[key]

我现在拥有的最好的测试代码是:

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返回了func,但是错误是由promiseA引发的。

所以我的问题是:如果是我想的那样,如何在嵌套的Promise函数中测试内部Promise函数。

我仍然在开玩笑并保证,如果代码结构不太适合测试或正常开发,请毫不犹豫地指出。非常感谢您在这里为我提供帮助。

1 个答案:

答案 0 :(得分:2)

您需要在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);
    });
};