如何测试是否正确调用了setTimeout?

时间:2018-05-11 20:32:07

标签: unit-testing mocha settimeout sinon

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,但它仍然会最终超时。我做错了什么?

1 个答案:

答案 0 :(得分:1)

在mocha中,我将超时设置如下:

it("send message", function(done) {
    this.timeout(15000);
    setTimeout(() => {
           ...
           done()
     }, 5000);
  })

注意一件事:我正在使用"功能"所以"这个"是正确的对象。

From Site

相关问题