unit-testing - 如何测试 setTimeout 是否被正确调用?

标签 unit-testing mocha.js 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);
  });

这次超时了。我增加了测试函数的超时,但它最终仍然会超时。我做错了什么?

最佳答案

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

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

注意一件事:我使用“function”,因此“this”是正确的对象。

From Site

关于unit-testing - 如何测试 setTimeout 是否被正确调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50299869/

相关文章:

java - 如何使用 JUnit 5 测试构造函数是否抛出异常?

带循环的 Python doctest

c++ - QT造物主: How to generate the library and testing executable for a custom widget

javascript - 如何将从外部范围调用的方法 stub 到被测函数?

python - 使用 Google AppEngine 在 Python 中进行单元测试和模拟电子邮件发件人

javascript - Mocha的基本功能 'describe/before/it'是如何实现的?

javascript - 使用 ES6 模块时,设置了 --watch 标志的 Mocha 会引发错误

javascript - 当在函数内部调用并使用从父级传递的参数时,为什么 setTimeout 函数记录未定义?

javascript setTimeout 或 jquery delay - 两者都不适合我

javascript - onBlur 杀死 onClick 但如果使用 setTimeout 则不会