在我的 Mocha 测试套件中,我想测试一个在幕后进行异步调用的功能。如何等待异步调用完成?
例如,我连续两次进行后调用。第一个 post 调用也会在内部进行异步调用,直到该异步操作完成后,第二个 post 调用才会通过。
我需要以下任一:
1) 在两个 post 调用之间设置延迟,以确保第一个 post 中的异步部分完成。
2) 重复进行第二个post调用,直到通过。
3)或者如何通过mocha-chai测试异步调用?
下面是示例:
describe('Back to back post calls with asynchronous operation', ()=> {
it('1st and 2nd post', (done) => {
chai.request(server)
.post('/thisis/1st_post')
.send()
.end((err, res) => {
expect(res.statusCode).to.equal(200);
/* HERE I Need A Delay or a way to call
the below post call may be for 5 times */
chai.request(server)
.post('/thisis/second_post')
.send()
.end((err, res) => {
expect(res.statusCode).to.equal(200);
});
done();
});
});
});
有办法解决这个问题吗?请帮忙。
谢谢。
最佳答案
为了使用 mocha 测试异步函数,您有以下可能性
use
done
only after the last callback in your sequence was executed
it('1st and 2nd post', (done) => {
chai.request(server)
.post('/thisis/1st_post')
.send()
.end((err, res) => {
expect(res.statusCode).to.equal(200);
/* HERE I Need A Delay or a way to call
the below post call may be for 5 times */
chai.request(server)
.post('/thisis/second_post')
.send()
.end((err, res) => {
expect(res.statusCode).to.equal(200);
//call done only after the last callback was executed
done();
});
});
});
use
done
callback with promises
describe('test', () => {
it('should do something async', (done) => {
firstAsyncCall
.then(() => {
secondAsyncCall()
.then(() => {
done() // call done when you finished your calls
}
})
});
})
经过适当的重构后,你会得到类似的东西
describe('test', () => {
it('should do something async', (done) => {
firstAsyncCall()
.then(secondAsyncCall())
.then(() => {
// do your assertions
done()
})
.catch(done)
})
})
use
async await
, much cleaner
describe('test', () => {
it('should do something async', async () => {
const first = await firstAsyncCall()
const second = await secondAsyncCall()
// do your assertion, no done needed
});
})
另一个需要记住的时刻是运行 mocha 测试时的 --timeout
参数。默认情况下,mocha 等待 2000
毫秒,当服务器响应较慢时,您应该指定更大的等待时间。
Mocha --超时 10000
关于node.js - 如何使用 mocha chai 测试异步服务器代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193413/