We have a simple wait method leveraging promises in our node app
exports.wait = (timeout) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, timeout)
});
};
We tried to test this behavior using sinon and chai.
We managed to get a proper assertion using chai-as-promised but it only check the promise resolves, without being able for us to test the real behavior:
- when passing a value of 100 ms to the wait method
- we expect the promise not to resolve at 99ms
- we expect the promise to resolve at 100ms
The combination of promise with timers is really what gets us headaches.
Here is our last try setup:
const chai = require('chai');
const expect = chai.expect;
const sinon = require('sinon');
chai.use(require('sinon-chai'));
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const wait = require('./wait').wait;
var clock;
before(() => {
clock = sinon.useFakeTimers();
});
after(() => {
clock.restore();
})
it('should not resolve until given time', (done) => {
const promise = wait(100);
let fulfilled = false;
promise.then(() => {
fulfilled = true;
done();
});
clock.tick(99);
expect(fulfilled).to.be.false;
clock.tick(2);
expect(fulfilled).to.be.true;
});
But fulfilled
is never flipped to true, or at least we cannot read it.
AssertionError: expected false to be true
How then mix timers with promise testing under chai - sinon to asset properly our timed resolve?