I'm having a problem with a timeout inside an async test. I'm using mocha ~1.20.1 and chai ~1.9.1.
I have other async tests running and they work, but they do not use setTimeout. I've tried changing the duration, but that hasn't worked also.
I would expect the output to be something like this
✓ should deliver successful response (291ms)
but it just gives me a line as if it was ran synchronously
1) should return true when token is expired based on time
test
it( 'should return true when token is expired based on time', function( done ) {
var AuthClient = new Client({
clientId: 'test'
, clientSecret: 'test'
, expiration: 1
});
setTimeout( function() {
expect( AuthClient.checkExpired() ).to.be.true;
done();
}, 1000 );
});
Error
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:139:19)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
@vernak2539 Out of curiosity, does the behavior change if you remove the spaces around the done parameter?
@boneskull I'll take a look, and let you know
@boneskull for some reason it's working as is now. I'm not sure what was going wrong, or why it magically started working. I appreciate the help though!
I had the same problem. It drove me damn crazy. Finally I found setTimeout() does not work properly while you have fake timer in your code, simply remove sinon.useFakeTimers() :
var clock = sinon.useFakeTimers(); // Remove this line.
I made a Promise function which does the delay as promises work better with async/await:
function timeout(fn, delay) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
fn();
resolve();
} catch(err) {
reject(err);
}
}, delay);
});
}
And using it:
it('resolves new value from cache after expiry time', async () => {
const cacheFn = () => cache.resolve('asyncItem', () => Math.random(), '1s');
const firstValue = await cacheFn();
const cachedValueBefore = await cacheFn();
expect(firstValue).to.eql(cachedValueBefore);
return timeout(async () => {
const cachedValueAfter = await cacheFn();
expect(firstValue).to.not.eql(cachedValueAfter);
}, 1100);
});
Most helpful comment
I had the same problem. It drove me damn crazy. Finally I found setTimeout() does not work properly while you have fake timer in your code, simply remove sinon.useFakeTimers() :
var clock = sinon.useFakeTimers(); // Remove this line.