Testing Debounced and Throttled Updates
You'll learn how to test components with debounced or throttled logic without waiting for real-time delays in your test suite.
The Problem with Time-Based Updates
When your components use debouncing (waiting for a pause in activity) or throttling (limiting update frequency), testing them with real timers would make your tests painfully slow. A 500ms debounce would force each test to wait half a second—multiply that across hundreds of tests and you're waiting minutes for results.
Fake Timers to the Rescue
Vitest provides vi.useFakeTimers() to replace real timers with controllable ones. You can then use vi.advanceTimersByTime(milliseconds) to instantly "fast-forward" time without actually waiting.
Think of it like a video player's scrub bar—instead of watching the whole video, you jump to the timestamp you need.
The Testing Pattern
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { vi } from 'vitest';
import SearchInput from './SearchInput'; // debounces after 300ms
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.restoreAllMocks();
});
test('debounces search input', async () => {
render(<SearchInput onSearch={vi.fn()} />);
const input = screen.getByRole('textbox');
await userEvent.type(input, 'react');
// Before debounce time: nothing called yet
expect(onSearch).not.toHaveBeenCalled();
// Fast-forward past the debounce delay
vi.advanceTimersByTime(300);
// Now it should have fired
expect(onSearch).toHaveBeenCalledWith('react');
});
Always clean up with vi.restoreAllMocks() or vi.useRealTimers() to avoid affecting other tests.
Key Takeaway: Use vi.useFakeTimers() and vi.advanceTimersByTime() to test debounced/throttled logic instantly, making your tests fast and predictable without sacrificing real-world timer behavior coverage.