February 2019
Intermediate to advanced
204 pages
4h 52m
English
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); ...Read now
Unlock full access