Time mocks

JavaScript provides a handful of timer functions, including setTimeout, setInterval, clearTimeout, and clearInterval. These codes can be tested using Jest, too. Let's consider a simple function that displays the start of the game and ends the game after two seconds:

function takeXray(callback) {
console.log("Ready, close your eye.");
setTimeout(() => {
console.log("Great you are done.");
callback && callback();
}, 2000);
}
module.exports = takeXray;

Now, let's test our function, called takeXray:

jest.useFakeTimers();
test("waits 2 second before taking the x-ray", () => {
const takeXray = require("../time");
takeXray();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 2000);
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset