Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}

My test is

  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);
  });

This times out. I've increased the timeout of the test function, but it'll still ultimately timeout. What am I doing wrong?

like image 233
Shamoon Avatar asked Nov 08 '22 07:11

Shamoon


1 Answers

In mocha I set the timeout as follows:

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

Notice one thing: I am using "function" so that "this" is the correct object.

From Site

like image 111
Vlad Avatar answered Nov 14 '22 01:11

Vlad