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

Testing API Responses, Not Fetch Internals

Assert that data appears on screen after loading, not that useEffect called fetch with correct arguments.

Testing API Responses, Not Fetch Internals

What you'll learn: How to write resilient API tests by focusing on what users see, not how the data was fetched.

The Wrong Way to Test

When a component fetches data, beginners often test how the fetching happens:

// ❌ Brittle implementation test
test('calls fetch with correct URL', () => {
  const fetchSpy = vi.spyOn(global, 'fetch');
  render(<UserProfile userId="123" />);
  
  expect(fetchSpy).toHaveBeenCalledWith('/api/users/123');
});

This test breaks if you switch from fetch to axios, or move the API call to a custom hook, or add query parameters. The user doesn't care how you fetched the data.

The Right Way: Test What Appears

Instead, assert that the result of the API call renders correctly:

// ✅ Behavior-focused test
test('displays user name after loading', async () => {
  // MSW already configured to return mock data
  render(<UserProfile userId="123" />);
  
  expect(await screen.findByText('Loading...')).toBeInTheDocument();
  expect(await screen.findByText('Jane Doe')).toBeInTheDocument();
});

You're testing:

  • Loading state appears (user sees feedback)
  • Data eventually renders (user sees their information)

You're not testing:

  • Which fetching library was used
  • What useEffect dependencies triggered it
  • How many times fetch was called

The Mental Model

Think of your component as a black box: data goes in (via API), UI comes out. Test the UI transformation, not the plumbing inside the box.

Key Takeaway: Test that correct data appears on screen after an API call completes, not that fetch was called with specific arguments—refactoring implementation details shouldn't break your tests.