在计时器内嵌套异步等待-未返回所需值 [英] Nested Async await inside timer - not returning the desired value

查看:47
本文介绍了在计时器内嵌套异步等待-未返回所需值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用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;

});

这篇关于在计时器内嵌套异步等待-未返回所需值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆