mardi 21 avril 2015

How to fake Bluebird's timers in tests?

I have a function which makes use of Bluebird's Promise.delay() method to recursively check on the status of a long-running task every 5 seconds:

waitForLongRunningTask: function (taskId) {
  return checkTaskStatus(taskId)
  .then(function (result) {
    if (result.status == 'success') {
      return Promise.resolve(result);
    }
    if (result.status == 'failure') {
      return Promise.reject(result);
    }
    return Promise.delay(5000)
    .then(function () {
      return waitForLongRunningTask(taskId);
    });
  });
}

How can I get the tested function to finish immediately rather than waiting for the real duration?

Currently I am doing this in my test setup, which works, but seems heavy-handed, and won't work with the other Bluebird timer methods.

// beforeEach
this.sandbox = sinon.sandbox.create();
this.sandbox.stub(Promise, 'delay', Promise.resolve);

// afterEach
this.sandbox.restore();

Is there a better way, using, e.g., Sinon's useFakeTimers()? When I tried that, the tests would just time out after 20 seconds.

I am using bluebird 2.9.24, mocha 1.21.5, sinon 1.14.1, and node 0.10.38.

Aucun commentaire:

Enregistrer un commentaire