Timer Mocks
The native timer functions (i.e., setTimeout()
, setInterval()
, clearTimeout()
, clearInterval()
) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. Great Scott!
info
Also see Fake Timers API documentation.
Enable Fake Timers
In the following example we enable fake timers by calling jest.useFakeTimers()
. This is replacing the original implementation of setTimeout()
and other timer functions. Timers can be restored to their normal behavior with jest.useRealTimers()
.
timerGame.js
function timerGame(callback) {
console.log('Ready....go!');
setTimeout(() => {
console.log("Time's up -- stop!");
callback && callback();
}, 1000);
}
module.exports = timerGame;
__tests__/timerGame-test.js
jest.useFakeTimers();
jest.spyOn(global, 'setTimeout');
test('waits 1 second before ending the game', () => {
const timerGame = require('../timerGame');
timerGame();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
});