我必须使用 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 响应,并且我的测试失败。请让我知道这段代码哪里出了问题。
不要使用setInterval
有承诺,并且从不通过async function
作为忽略返回的承诺时的回调。在您的情况下,请改用循环:
async function getData (userId) {
let response;
do {
await delay(10000);
response = await superagent.get("localhost:3000/user/details/").query({'user': userId}).type('application/json');
} while(response.body["status"] != 'DONE');
return superagent.get("localhost:3000/user/details/get").type('application/json');
}
with
function delay(t) {
return new Promise(resolve => setTimeout(resolve, t));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)