如何测试是否正确调用了 setTimeout?
How can I test if a setTimeout was called appropriately?
function restartService(startTime) {
const endTime = (new Date()).getTime();
const fiveMinLeft = 5 * 60 * 1000 - (endTime - startTime);
console.log(startTime, endTime, fiveMinLeft);
setTimeout(() => {
console.log('clock');
Producer.create({
queueUrl: process.env.MY_QUEUE
}).send([{
stuff: true
}], (err) => {
console.log('err', err);
});
}, fiveMinLeft);
return Promise.resolve();
}
我的测试是
it.only('send a message after 5 minutes to the queue', (done) => {
const msg = 'msg'
const sendStub = sinon.spy();
const clock = sinon.useFakeTimers();
sinon.stub(global.db.Deposit, 'findAll').returns(Promise.resolve([{
id: 2
}]));
sinon.stub(global.db.Transaction, 'findOrCreate').returns(Promise.resolve());
sinon.stub(Producer, 'create').returns({
send: sendStub
});
WatcherService.handleMessage(msg, () => {
global.db.Transaction.findOrCreate.restore();
global.db.Deposit.findAll.restore();
Producer.create.should.be.called();
done();
});
clock.tick(5 * 1000 * 60);
});
这次超时了。我已经增加了测试功能的timeout
,但它最终还是会超时。我做错了什么?
在摩卡我设置超时如下:
it("send message", function(done) {
this.timeout(15000);
setTimeout(() => {
...
done()
}, 5000);
})
注意一件事:我正在使用 "function",因此 "this" 是正确的对象。
function restartService(startTime) {
const endTime = (new Date()).getTime();
const fiveMinLeft = 5 * 60 * 1000 - (endTime - startTime);
console.log(startTime, endTime, fiveMinLeft);
setTimeout(() => {
console.log('clock');
Producer.create({
queueUrl: process.env.MY_QUEUE
}).send([{
stuff: true
}], (err) => {
console.log('err', err);
});
}, fiveMinLeft);
return Promise.resolve();
}
我的测试是
it.only('send a message after 5 minutes to the queue', (done) => {
const msg = 'msg'
const sendStub = sinon.spy();
const clock = sinon.useFakeTimers();
sinon.stub(global.db.Deposit, 'findAll').returns(Promise.resolve([{
id: 2
}]));
sinon.stub(global.db.Transaction, 'findOrCreate').returns(Promise.resolve());
sinon.stub(Producer, 'create').returns({
send: sendStub
});
WatcherService.handleMessage(msg, () => {
global.db.Transaction.findOrCreate.restore();
global.db.Deposit.findAll.restore();
Producer.create.should.be.called();
done();
});
clock.tick(5 * 1000 * 60);
});
这次超时了。我已经增加了测试功能的timeout
,但它最终还是会超时。我做错了什么?
在摩卡我设置超时如下:
it("send message", function(done) { this.timeout(15000); setTimeout(() => { ... done() }, 5000); })
注意一件事:我正在使用 "function",因此 "this" 是正确的对象。