Course contentsShow
← React
Lesson 2146 of 2,39647. Testing Patterns and Best PracticesFree lesson

Testing Components That Fetch Data

Mock fetch calls with MSW, render the component, and wait for loading states to resolve before asserting final UI.

Testing Components That Fetch Data

You'll learn: How to write robust tests for components that fetch data by mocking network requests, rendering the component, and asserting the UI after async operations complete.

The Complete Testing Pattern

When a component fetches data on mount or through user interaction, your test needs to follow a specific flow: set up mock network responses (using MSW), render the component, wait for the loading state to resolve, then assert the final UI state.

Think of it like testing a vending machine. You don't just check if the buttons work—you need to verify: the "processing" light turns on, the machine reaches out to inventory, and finally the correct snack appears.

The Three-Phase Approach

1. Mock the Network Request

Use MSW handlers to define what your API should return:

http.get('/api/users', () => {
  return HttpResponse.json([{ id: 1, name: 'Alice' }])
})

2. Render and Wait

Render your component and use findBy or waitFor to wait for async operations:

render(<UserList />)

// Wait for loading to finish and data to appear
const user = await screen.findByText('Alice')
expect(user).toBeInTheDocument()

3. Assert Final State

Verify the loading state is gone and the correct data displays:

expect(screen.queryByText('Loading...')).not.toBeInTheDocument()

You can also test the loading state explicitly by asserting it appears before awaiting the final state.

Key Takeaway: Testing data-fetching components requires mocking network requests with MSW, rendering the component, waiting for async updates with findBy or waitFor, then asserting both that loading states resolve and the correct data appears in the UI.