Testing API Calls

In this lesson we will go over some approaches to testing API calls.

We are going to focus on mocking window.fetch calls, returning mock data, and checking that the correct endpoint was called.

We will be assuming you are using jest-fetch-mock or vitest-fetch-mock - both behave in a similar way. In your app you will first need to install one of those and follow its setup guide:

  • Jest (with jest-fetch-mock): call enableMocks()
  • Vitest (with vitest-fetch-mock): create a fetch mock with createFetchMock(vi) and then call enableMocks(). See their README for details.

For the interactive examples in this lesson, the fetch mock has already been configured and is ready to use.

We plan to write a future lesson on Mock Service Worker (MSW) too.

What we will be testing

This is the component that we will be testing today.

Basically it just calls the /api/data endpoint, in a useEffect, and it renders out a list of items with item.name.

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        '/api/data'
      );
      const fetchedData =
        await response.json();
      setData(fetchedData);
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>My Component</h1>
      <ul>
        {data.map(item => (
          <li
            key={item.id}
            data-testid={`item-id-${item.id}`}
          >
            {item.name}
          </li>
        ))}
      </ul>
    </div>
  );
};

We want to write tests that check:

  • Do we render expected (mock response) data?
  • Does it make a window.fetch call to the /api/data endpoint?
  • Does it handle loading states correctly?
  • Does it handle API errors?

Loading full lesson content & code...

Ready to try running tests for this lesson?