Step-by-Step Guide: How to Mock API Calls in React Tests using React Testing Library

Babux
3 min readJul 18, 2023

When testing React components that make API calls, it’s essential to isolate your tests from external dependencies and ensure they run reliably in different environments. Mocking API calls allows you to simulate responses and control the behavior of your API requests during testing. In this step-by-step guide, we will explore how to mock API calls in React tests using React Testing Library. We’ll provide example codes to illustrate each step of the process.

Step 1: Install Dependencies Start by installing the necessary dependencies: react-testing-library and msw (Mock Service Worker).

npm install --save-dev @testing-library/react msw

Step 2: Set Up a Mock Service Worker (MSW) Server Create a file called src/setupTests.js and configure your Mock Service Worker server.

jsxCopy code
// src/setupTests.js
import { setupServer } from 'msw/node';
import { handlers } from './mocks/handlers';
// Set up a Mock Service Worker server with the provided request handlers
const server = setupServer(...handlers);
// Start the server before running your tests
beforeAll(() => server.listen());
// Reset and stop the server after all tests finish
afterAll(() => server.resetHandlers(), server.close());

Step 3: Define Request Handlers Create a folder called src/mocks and inside it, create a file called handlers.js. This is where you define the request handlers to intercept and mock your API calls.

// src/mocks/handlers.js
import { rest } from 'msw';
export const handlers = [
rest.get('/api/data', (req, res, ctx) => {
// Simulate a successful response with mock data
return res(
ctx.status(200),
ctx.json({ data: 'Mocked response' })
);
}),
];

Step 4: Implement the Mocked API Call in Your Test In your test file, import the necessary functions from react-testing-library and msw. Use the server instance to handle the requests and provide the desired mock response.

import { render, screen } from '@testing-library/react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
rest.get('/api/data', (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({ data: 'Mocked response' })
);
}),
);
beforeAll(() => server.listen());
afterAll(() => server.close());
test('displays data from API', async () => {
render(<YourComponent />);
const dataElement = await screen.findByText('Mocked response');
expect(dataElement).toBeInTheDocument();
});

Step 5: Run Your Tests Now you can run your tests with the mocked API call. The server will intercept the requests and provide the defined responses, allowing you to test your component's behavior without relying on the actual API.

npm test

Mocking API calls in React tests using React Testing Library and Mock Service Worker is a powerful technique to ensure reliable and isolated tests. By following this step-by-step guide, you can set up a mock server, define request handlers, and implement the mocked API call in your tests. This approach enables you to simulate different responses, test edge cases, and verify the behavior of your components without making actual API requests. Happy testing!

--

--

Babux

I broke into tech from a non traditional background. I work as a software engineer and I share what I learned and what i think is important with you all!