Course contentsShow
← React
Lesson 2092 of 2,39646. Testing React with RTLFree lesson

Testing User-Triggered Fetches

Simulate user interactions that trigger requests, verify MSW handlers respond, check UI updates.

Testing User-Triggered Fetches

What you'll learn: How to test requests triggered by user actions like clicks, ensuring MSW intercepts them and your UI updates correctly.

The Scenario

Not all fetches happen on mount—many occur when users click buttons, submit forms, or interact with your UI. Testing these requires simulating the user action, then verifying both the network request and resulting UI changes.

The Pattern

You've already set up MSW handlers in your test file. Now you need to:

  1. Render the component containing the interactive element
  2. Simulate the user action with user-event (clicking a "Load More" button, submitting a form, etc.)
  3. Wait for the async UI update that should follow the successful fetch
  4. Assert the new content appears
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from './mocks/server';
import UserProfile from './UserProfile';

test('loads user data when button is clicked', async () => {
  server.use(
    http.get('/api/user', () => {
      return HttpResponse.json({ name: 'Alice', role: 'Admin' });
    })
  );

  const user = userEvent.setup();
  render(<UserProfile />);

  const loadButton = screen.getByRole('button', { name: /load profile/i });
  await user.click(loadButton);

  // Wait for async fetch and UI update
  expect(await screen.findByText('Alice')).toBeInTheDocument();
  expect(screen.getByText('Admin')).toBeInTheDocument();
});

Why This Works

MSW intercepts the request when your code makes it—it doesn't matter whether that happens in useEffect or a click handler. You're testing the complete user flow: action → request → response → UI update.

Key Takeaway: Test user-triggered fetches by simulating the interaction with user-event, letting MSW handle the network, and asserting the resulting DOM changes—exactly as a real user would experience it.