Course contentsShow
← JavaScript
Lesson 2701 of 2,72354. Testing in JavaScriptFree lesson

Mocking Timers: jest.useFakeTimers()

Control time in tests by mocking setTimeout, setInterval, and Date with fake timers.

Mocking Timers: jest.useFakeTimers()

You'll learn how to take control of time itself in your tests by replacing JavaScript's native timer functions with mock versions you can manually advance.

Why Mock Timers?

Imagine testing a function that waits 5 minutes before executing. Your test suite would take forever! Worse, testing code that uses setTimeout, setInterval, or checks Date.now() introduces real time delays and unpredictable behavior. Mocking timers lets you skip the waiting and control exactly when time "moves forward."

How It Works

When you call jest.useFakeTimers(), Jest replaces the native setTimeout, setInterval, clearTimeout, clearInterval, and Date with mock implementations. Time stops advancing automatically—it only moves when you tell it to with methods like jest.advanceTimersByTime() or jest.runAllTimers().

jest.useFakeTimers();

test('executes callback after timeout', () => {
  const callback = jest.fn();
  
  setTimeout(callback, 1000);
  
  expect(callback).not.toHaveBeenCalled();
  
  jest.advanceTimersByTime(1000); // Fast-forward 1 second
  
  expect(callback).toHaveBeenCalled();
});

Common Timer Control Methods

  • jest.advanceTimersByTime(ms) — move time forward by specific milliseconds
  • jest.runAllTimers() — exhaust all pending timers immediately
  • jest.runOnlyPendingTimers() — run only currently scheduled timers (useful with intervals)
  • jest.clearAllTimers() — cancel all pending timers

Always call jest.useRealTimers() after tests that use fake timers to restore normal behavior for subsequent tests.

Key Takeaway: jest.useFakeTimers() replaces native timer functions with controllable mocks, letting you test time-dependent code instantly and deterministically without actual waiting.