author avatar

amber.srivastava

Thu Nov 21 2024

Mocking Timers for Controlled Testing

If your code uses setTimeout or setInterval, Jest's timer mocking lets you fast-forward time.
Example: Using jest.useFakeTimers()



jest.useFakeTimers();

test("delayed greeting is sent after 3 seconds", () => {
  const callback = jest.fn();

  setTimeout(() => callback("Hello!"), 3000);
  jest.runAllTimers();

  expect(callback).toHaveBeenCalledWith("Hello!");
});


#CCT1JMA0Z # testing #jest