React › Testing

How would you test a component that fetches data when it first appears on the screen?

Intermediate

Answer

You typically mock the actual fetch function or API call so your test does not depend on a real network request, providing fake sample data instead, then use React Testing Library's asynchronous utilities, like waitFor or findBy queries, to wait for the component to finish updating after the fake data resolves.
test('shows user name after loading', async () => {
  jest.spyOn(global, 'fetch').mockResolvedValue({
    json: () => Promise.resolve({ name: 'Alice' }),
  });

  render(<UserProfile userId={1} />);
  const name = await screen.findByText('Alice');
  expect(name).toBeInTheDocument();
});
Real-world example A team writes a reliable, fast test for their user profile component by mocking the fetch call with fake sample data, avoiding the need for a real, slow, and unpredictable network request during every test run.

Common follow-ups: Why is mocking network requests generally preferred over making real API calls during tests?;What is the difference between findBy and waitFor when testing asynchronous behavior?