Testing Components That Fetch on Mount
You'll learn how to test components that trigger API requests when they first render—waiting for data to load and asserting on the results.
The Challenge of Mount-Time Fetching
Many real-world components fetch data immediately in a useEffect(() => { fetch(...) }, []) hook. When testing these, you can't make assertions on the loaded data right after render()—it hasn't arrived yet! The component goes through a loading state first.
This is where findBy queries shine. Unlike getBy (which fails immediately if nothing's found), findBy queries return a promise that repeatedly checks for an element, waiting up to 1000ms by default.
The Testing Pattern
import { render, screen } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { server } from './mocks/server';
import { UserProfile } from './UserProfile';
test('displays user data after loading', async () => {
server.use(
http.get('/api/user', () => {
return HttpResponse.json({ name: 'Alice', role: 'Engineer' });
})
);
render(<UserProfile userId="123" />);
// Initially shows loading state
expect(screen.getByText(/loading/i)).toBeInTheDocument();
// Wait for the data to appear (findBy waits asynchronously)
const userName = await screen.findByText('Alice');
expect(userName).toBeInTheDocument();
const userRole = screen.getByText('Engineer');
expect(userRole).toBeInTheDocument();
// Loading indicator should be gone
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});
Notice: MSW intercepts the request, the component renders with loading UI, then findByText waits for "Alice" to appear once the mocked response resolves.
Key Takeaway: Use findBy queries to wait for async data in components that fetch on mount—they return promises that resolve when the element appears, perfectly matching real user experience.