Advancing Time with jest.advanceTimersByTime
What you'll learn: How to fast-forward fake timers instantly to trigger scheduled callbacks without waiting in real time.
The Problem with Real Time in Tests
Once you've enabled jest.useFakeTimers(), your setTimeout() and setInterval() calls no longer execute automatically. They're frozen, waiting for you to tell Jest to move time forward. This is where jest.advanceTimersByTime() comes in.
Fast-Forwarding the Clock
Think of fake timers like a video player on pause. jest.advanceTimersByTime(milliseconds) is the fast-forward button—it jumps ahead by the exact number of milliseconds you specify, triggering any callbacks scheduled within that window.
test('executes callback after timeout', () => {
jest.useFakeTimers();
const callback = jest.fn();
setTimeout(callback, 1000);
// Nothing has happened yet
expect(callback).not.toHaveBeenCalled();
// Jump forward 1000ms
jest.advanceTimersByTime(1000);
// Now the callback has executed
expect(callback).toHaveBeenCalledTimes(1);
});
Precise Control Over Multiple Timers
You can advance time in stages to test intermediate states:
test('handles multiple timeouts', () => {
jest.useFakeTimers();
const first = jest.fn();
const second = jest.fn();
setTimeout(first, 500);
setTimeout(second, 1500);
jest.advanceTimersByTime(500);
expect(first).toHaveBeenCalled();
expect(second).not.toHaveBeenCalled();
jest.advanceTimersByTime(1000); // Total: 1500ms
expect(second).toHaveBeenCalled();
});
This gives you surgical precision: test exactly what happens at 500ms, at 1000ms, or at any point in your async timeline—all without waiting a single real millisecond.
Key Takeaway: jest.advanceTimersByTime(ms) lets you instantly fast-forward fake timers by a specific duration, triggering all callbacks scheduled within that time window for precise, instant async testing.