Jest Timer Mocks and Advanced Async Testing

Jest Timer Mocks and Advanced Async Testing

Jest's fake timers replace setTimeout, setInterval, Date, and related globals with controlled implementations. Instead of waiting 5 seconds for a timer to fire, you call jest.advanceTimersByTime(5000) and it fires immediately. This makes tests for debounced inputs, polling functions, retry logic, and time-based expiry both fast and deterministic. Combine fake timers with async/await and act() (for React) to test complex asynchronous flows without real delays.

Key Takeaways

Fake timers make time-based tests fast and deterministic. Without fake timers, a test for a 30-second polling interval actually waits 30 seconds. With jest.useFakeTimers(), you control time programmatically.

jest.advanceTimersByTime() fires all timers that would have fired in that duration. It's sequential—timers fire in order, and timers scheduled by fired timers also fire if they fall within the advanced window.

jest.runAllTimers() fires everything. It runs all pending timers, including nested timers created by timers. Useful for draining a timer queue completely, dangerous for infinite intervals (use jest.runAllTimersAsync() or jest.advanceTimersByTime() instead).

jest.useFakeTimers() must be paired with jest.useRealTimers() or afterEach cleanup. Fake timers leak between tests if not cleaned up, causing mysterious ordering failures.

Async tests with fake timers need careful ordering of advanceTimersByTime and await. Timer advancement is synchronous; Promise resolution is microtask-based. Use await Promise.resolve() to flush the microtask queue after advancing timers.

Enabling Fake Timers

describe('Timer tests', () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.useRealTimers();   // Always restore real timers
    jest.clearAllTimers();  // Clear any pending timers
  });
});

Or configure globally:

// jest.config.js
module.exports = {
  fakeTimers: {
    enableGlobally: true,
  },
};

Basic Timer Control

setTimeout

function delayedAction(callback, delay) {
  setTimeout(callback, delay);
}

test('fires callback after delay', () => {
  const callback = jest.fn();
  delayedAction(callback, 3000);

  expect(callback).not.toHaveBeenCalled(); // Not fired yet

  jest.advanceTimersByTime(2999);
  expect(callback).not.toHaveBeenCalled(); // Still not fired

  jest.advanceTimersByTime(1);             // 3000ms total
  expect(callback).toHaveBeenCalledTimes(1);
});

setInterval

function startHeartbeat(callback, interval) {
  return setInterval(callback, interval);
}

test('fires on each interval', () => {
  const callback = jest.fn();
  const id = startHeartbeat(callback, 1000);

  jest.advanceTimersByTime(3500);
  expect(callback).toHaveBeenCalledTimes(3); // At 1000, 2000, 3000ms

  clearInterval(id);
});

jest.runAllTimers()

function scheduleWork() {
  setTimeout(() => {
    setTimeout(() => {
      setTimeout(() => console.log('done'), 100);
    }, 100);
  }, 100);
}

test('runs all nested timers', () => {
  const spy = jest.spyOn(console, 'log');
  scheduleWork();

  jest.runAllTimers(); // Runs all three timers in order

  expect(spy).toHaveBeenCalledWith('done');
});

Warning: jest.runAllTimers() will infinite-loop on self-rescheduling intervals. Use jest.advanceTimersByTime() for those.

Debounce Testing

Debounce is a classic fake timer use case:

// utils/debounce.js
export function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
// utils/debounce.test.js
import { debounce } from './debounce';

describe('debounce', () => {
  beforeEach(() => jest.useFakeTimers());
  afterEach(() => jest.useRealTimers());

  test('calls function after delay', () => {
    const fn = jest.fn();
    const debouncedFn = debounce(fn, 300);

    debouncedFn('arg1');
    expect(fn).not.toHaveBeenCalled();

    jest.advanceTimersByTime(300);
    expect(fn).toHaveBeenCalledWith('arg1');
  });

  test('only calls function once for rapid invocations', () => {
    const fn = jest.fn();
    const debouncedFn = debounce(fn, 300);

    debouncedFn('call1');
    debouncedFn('call2');
    debouncedFn('call3');

    jest.advanceTimersByTime(300);

    expect(fn).toHaveBeenCalledTimes(1);
    expect(fn).toHaveBeenCalledWith('call3'); // Last call wins
  });

  test('calls function multiple times after quiet periods', () => {
    const fn = jest.fn();
    const debouncedFn = debounce(fn, 300);

    debouncedFn('first');
    jest.advanceTimersByTime(300);     // First fires

    debouncedFn('second');
    jest.advanceTimersByTime(300);     // Second fires

    expect(fn).toHaveBeenCalledTimes(2);
    expect(fn).toHaveBeenNthCalledWith(1, 'first');
    expect(fn).toHaveBeenNthCalledWith(2, 'second');
  });
});

Async Timers with Promises

When timers resolve Promises, you need to flush the microtask queue after advancing time:

// retry.js
export async function retryOperation(fn, maxAttempts, delayMs) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt === maxAttempts) throw err;
      await new Promise(resolve => setTimeout(resolve, delayMs));
    }
  }
}
// retry.test.js
describe('retryOperation', () => {
  beforeEach(() => jest.useFakeTimers());
  afterEach(() => jest.useRealTimers());

  test('retries failed operations', async () => {
    const fn = jest.fn()
      .mockRejectedValueOnce(new Error('fail 1'))
      .mockRejectedValueOnce(new Error('fail 2'))
      .mockResolvedValueOnce('success');

    const promise = retryOperation(fn, 3, 1000);

    // First attempt fails, starts 1000ms wait
    await Promise.resolve(); // Flush microtasks (first rejection)

    jest.advanceTimersByTime(1000); // Fire the delay timer
    await Promise.resolve(); // Flush microtasks (timer resolves)

    // Second attempt fails, starts another 1000ms wait
    await Promise.resolve();

    jest.advanceTimersByTime(1000);
    await Promise.resolve();

    // Third attempt succeeds
    const result = await promise;
    expect(result).toBe('success');
    expect(fn).toHaveBeenCalledTimes(3);
  });
});

jest.advanceTimersByTimeAsync()

Jest 29.1+ provides an async version that automatically flushes microtasks:

test('retries with advanceTimersByTimeAsync', async () => {
  const fn = jest.fn()
    .mockRejectedValueOnce(new Error('fail'))
    .mockResolvedValueOnce('success');

  const promise = retryOperation(fn, 2, 1000);

  await jest.advanceTimersByTimeAsync(1000); // Advances time AND flushes microtasks

  const result = await promise;
  expect(result).toBe('success');
});

Testing Polling Functions

// polling.js
export function startPolling(fetchData, onData, interval) {
  let active = true;

  async function poll() {
    while (active) {
      try {
        const data = await fetchData();
        onData(data);
      } catch (e) {
        // ignore
      }
      await new Promise(resolve => setTimeout(resolve, interval));
    }
  }

  poll();

  return () => { active = false; };
}
test('polls at regular intervals', async () => {
  jest.useFakeTimers();
  const fetchData = jest.fn().mockResolvedValue({ count: 42 });
  const onData = jest.fn();

  startPolling(fetchData, onData, 5000);

  // Initial fetch
  await Promise.resolve();
  await Promise.resolve(); // Double flush for async functions
  expect(onData).toHaveBeenCalledTimes(1);

  // Advance through 3 polling cycles
  for (let i = 0; i < 3; i++) {
    await jest.advanceTimersByTimeAsync(5000);
  }

  expect(onData).toHaveBeenCalledTimes(4); // Initial + 3 polls
  jest.useRealTimers();
});

Mocking Date

describe('with mocked Date', () => {
  beforeEach(() => {
    jest.useFakeTimers();
    jest.setSystemTime(new Date('2026-01-01T00:00:00Z'));
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  test('generates timestamp at fixed time', () => {
    const event = createEvent('user-login');
    expect(event.timestamp).toBe('2026-01-01T00:00:00.000Z');
  });

  test('subscription expires after 30 days', () => {
    const subscription = createSubscription();

    // Advance 29 days
    jest.advanceTimersByTime(29 * 24 * 60 * 60 * 1000);
    expect(subscription.isExpired()).toBe(false);

    // Advance 1 more day (30 days total)
    jest.advanceTimersByTime(24 * 60 * 60 * 1000);
    expect(subscription.isExpired()).toBe(true);
  });
});

React Component Timer Testing

For React components that use timers, wrap timer advancement in act():

import { render, screen, act } from '@testing-library/react';
import Toast from './Toast';

test('toast disappears after 3 seconds', () => {
  jest.useFakeTimers();

  render(<Toast message="Success!" duration={3000} />);

  expect(screen.getByText('Success!')).toBeInTheDocument();

  act(() => {
    jest.advanceTimersByTime(3000);
  });

  expect(screen.queryByText('Success!')).not.toBeInTheDocument();

  jest.useRealTimers();
});

Common Mistakes

Mistake: Not cleaning up fake timers

// Bad: fake timers leak to next test
test('timer test', () => {
  jest.useFakeTimers();
  // ...
  // Missing jest.useRealTimers()!
});

Mistake: Forgetting to flush microtasks with async timers

// Bad: timer fires but Promise resolution hasn't been processed
jest.advanceTimersByTime(1000);
expect(asyncCallback).toHaveBeenCalled(); // May fail—microtasks not flushed

Mistake: jest.runAllTimers() on infinite intervals

// Bad: hangs Jest process
const id = setInterval(() => {}, 100);
jest.runAllTimers(); // INFINITE LOOP

Mistake: Using real Date.now() in code under fake timer control

// Your code uses Date.now() — fake timers don't control it unless you use jest.setSystemTime()
const timestamp = Date.now(); // May return real time even with fake timers

Summary

Jest fake timers are essential for testing any code that uses setTimeout, setInterval, or Date. The core workflow:

  1. jest.useFakeTimers() in beforeEach
  2. jest.useRealTimers() in afterEach
  3. jest.advanceTimersByTime(ms) for precise control
  4. await Promise.resolve() or jest.advanceTimersByTimeAsync() when timers resolve Promises
  5. jest.setSystemTime() to control new Date() and Date.now()

Read more

Start now free