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);
});
这次超时了。我增加了测试函数的超时
,但它最终仍然会超时。我做错了什么?
最佳答案
在 Mocha 中,我将超时设置如下:
it("send message", function(done) { this.timeout(15000); setTimeout(() => { ... done() }, 5000); })
注意一件事:我使用“function”,因此“this”是正确的对象。
关于unit-testing - 如何测试 setTimeout 是否被正确调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50299869/