waitFor: Waiting for Async Updates
What you'll learn: How to use waitFor to pause your test until asynchronous state changes and effects complete before checking results.
The Asynchronous Testing Challenge
When your component updates state after an async operation (like a fetch call or setTimeout), your test needs to wait for those updates to reflect in the DOM. If you assert immediately, you'll be checking the old state.
How waitFor Works
waitFor accepts a callback containing your assertions and repeatedly runs it until either the assertions pass or a timeout occurs (default 1000ms). It's like a patient observer that keeps checking "Has it happened yet? How about now?"
import { render, screen, waitFor } from '@testing-library/react';
import { UserProfile } from './UserProfile';
test('displays user data after loading', async () => {
render(<UserProfile userId="123" />);
// Initially shows loading state
expect(screen.getByText(/loading/i)).toBeInTheDocument();
// Wait for the async data to load and render
await waitFor(() => {
expect(screen.getByText('John Doe')).toBeInTheDocument();
});
});
When to Use waitFor
Use waitFor when:
- State updates happen after async operations (fetch, timers)
- Multiple state updates occur in sequence
- Effects trigger additional renders
- You need assertions that aren't tied to a single element appearing (use
findByfor that simpler case)
test('updates error count after failed submissions', async () => {
const { user } = render(<Form />);
await user.click(screen.getByRole('button', { name: /submit/i }));
await waitFor(() => {
expect(screen.getByText(/errors: 1/i)).toBeInTheDocument();
});
});
Key Takeaway: Use waitFor when you need to wait for async state updates and effects to complete before asserting; it retries your assertions until they pass or timeout, making your tests resilient to asynchronous timing.