Course contentsShow
← JavaScript
Lesson 2393 of 2,72349. Common Patterns and IdiomsFree lesson

Testing Debounce and Throttle

Use fake timers in tests to verify debounce and throttle behavior without waiting.

Testing Debounce and Throttle

You'll learn how to test time-dependent debounce and throttle functions without making your tests slow.

When you write tests for debounced or throttled functions, you face a problem: these utilities delay execution. Normally, you'd need to wait real seconds for timers to fire, making tests unbearably slow. The solution? Fake timers that let you control time itself in your tests.

The Problem with Real Timers

If your debounce waits 500ms before calling a function, a naive test would use setTimeout or async waits:

// Slow test - actually waits!
test('debounce waits 500ms', async () => {
  const fn = jest.fn();
  const debounced = debounce(fn, 500);
  
  debounced();
  await new Promise(resolve => setTimeout(resolve, 600));
  
  expect(fn).toHaveBeenCalled(); // Takes 600ms!
});

Using Fake Timers

Test frameworks like Jest provide jest.useFakeTimers() to mock setTimeout, setInterval, and clearTimeout. You then control time with jest.advanceTimersByTime():

test('debounce waits 500ms', () => {
  jest.useFakeTimers();
  const fn = jest.fn();
  const debounced = debounce(fn, 500);
  
  debounced();
  expect(fn).not.toHaveBeenCalled();
  
  jest.advanceTimersByTime(500);
  expect(fn).toHaveBeenCalledTimes(1); // Instant!
  
  jest.useRealTimers();
});

You can test rapid calls, cancellations, and throttle windows by "fast-forwarding" time without actual delays. This makes your test suite run in milliseconds instead of seconds.

Key Takeaway: Fake timers let you instantly verify debounce and throttle behavior by controlling time programmatically, keeping tests fast and deterministic.