Testing React applications that rely on API calls can be challenging. Mocking these API calls ensures your tests are reliable and do not depend on external services. One popular tool for mocking API calls in React testing is MSW (Mock Service Worker). This tutorial provides a step-by-step guide to mocking API calls using MSW in your React tests.

What is MSW?

MSW is a JavaScript library that intercepts network requests at the network level, allowing you to mock API responses seamlessly. It works in both browser and Node environments, making it versatile for frontend and backend testing.

Setting Up MSW in Your React Project

Follow these steps to integrate MSW into your React project:

  • Install MSW via npm or yarn:

npm: npm install msw --save-dev

Yarn: yarn add msw --dev

Creating Request Handlers

Create a new file, e.g., src/mocks/handlers.js, to define your mock API responses:

Example handler for a GET request:

import { rest } from 'msw';

export const handlers = [
  rest.get('/api/user', (req, res, ctx) => {
    return res(
      ctx.status(200),
      ctx.json({ id: 1, name: 'John Doe' })
    );
  }),
];

Setting Up the Service Worker

Generate the Service Worker file using the MSW CLI:

Run in your terminal:

npx msw init public/ --save

This command sets up the Service Worker in the public directory, which is required for browser testing.

Integrating MSW with Your Tests

Set up the MSW server in your test environment. For example, in your setupTests.js file:

import { setupServer } from 'msw/node';
import { handlers } from './mocks/handlers';

const server = setupServer(...handlers);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Writing a Test with Mocked API

Example test using React Testing Library:

import { render, screen, waitFor } from '@testing-library/react';
import UserComponent from './UserComponent';

test('fetches and displays user data', async () => {
  render();
  const userName = await waitFor(() => screen.getByText('John Doe'));
  expect(userName).toBeInTheDocument();
});

Conclusion

Using MSW for mocking API calls in React testing provides a realistic and flexible way to simulate server responses. It helps ensure your components handle data correctly without relying on actual backend services. Follow these steps to integrate MSW into your testing workflow and improve your test reliability.