在计时器内嵌套异步等待-未返回所需值

人气:538 发布:2022-10-16 标签: javascript node.js async-await chai mocha.js

问题描述

我必须使用Mocha和Chai测试测试端点的响应。下面是相同的代码:

async function getData (userId) {
        let response;
        let interval = setInterval(async () => {
            response = await superagent.get("localhost:3000/user/details/").query({'user': userId}).type('application/json');
            if (response.body["status"] == 'DONE') {
                clearInterval(interval);
                response = await superagent.get("localhost:3000/user/details/get").type('application/json');
            }
        }, 10000);

    return response;    

}

测试代码:

it('User Get Data', async function () {
        return getData(userId,).then(function (res) {
            expect(res).to.exist;
            expect(res.status).to.equal(200);
            expect(res.body).to.contain('operation');
            expect(res.body["userDetails"]).to.exist;


        });

我总是得到NULL响应,并且我的测试失败。请告诉我这个代码哪里出错了。

推荐答案

经过编辑以消除While循环:

您可以使用async/await重写getData,并将interval包装在承诺中。一旦第一个响应正常,请清除间隔,解析承诺,然后执行第二个呼叫。

在您的单元测试中,只需等待此函数,然后验证响应详细信息。请注意,您可能希望增加测试的默认mocha-timeout,因为这可能需要一段时间。类似于:

async function getData(userId) {

    const firstResponsePromise = new Promise(resolve => {
            const interval = setInterval(async() => {
                    const response = await superagent.get('localhost:3000/user/details/').query({
                            'user': userId
                        }).type('application/json');
                    if (response.body['status'] == 'DONE') {
                        clearInterval(interval);
                        resolve();
                    }

                }, 10000)
        });

    await firstResponsePromise;
    return superagent.get('localhost:3000/user/details/get').type('application/json');

}

// unit test

it('User Get Data', async function () {
    const res = await getData(userId);
    expect(res).to.exist;
    expect(res.status).to.equal(200);
    expect(res.body).to.contain('operation');
    expect(res.body["userDetails"]).to.exist;

});

194