πŸ§ͺ React Testing & Debugging
Estimated reading: 3 minutes 376 views

React Mocking APIs in Tests – Simulate Network Calls for Reliable Testing (2025 Guide)


Introduction – Why Mock APIs in React Tests?

React applications often rely on APIs to fetch or submit data. When testing such components, calling real APIs is slow, flaky, and unreliable.

Mocking APIs allows you to:

  • Speed up tests
  • Avoid actual network requests
  • Simulate API responses (success, error, delay)
  • Test components in isolation

In this guide, you’ll learn:

  • How to mock APIs using jest.fn(), fetch, and axios
  • Mock with MSW (Mock Service Worker)
  • Handle different HTTP methods and edge cases
  • Best practices for mocking external data in React Testing Library (RTL)

1. Mocking fetch with Jest

Component Example:

useEffect(() => {
  fetch('/api/data')
    .then(res => res.json())
    .then(setData);
}, []);

Test Example:

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve(['apple', 'banana']),
  })
);

test('renders fetched data', async () => {
  render(<Component />);
  expect(await screen.findByText('apple')).toBeInTheDocument();
});

Use findByText() or waitFor() for async assertions
Works for global fetch in most apps


2. Mocking Axios with Jest

Component:

import axios from 'axios';

useEffect(() => {
  axios.get('/api/items').then((res) => setItems(res.data));
}, []);

Test:

jest.mock('axios');

test('renders axios data', async () => {
  axios.get.mockResolvedValue({ data: ['apple', 'banana'] });

  render(<Component />);
  expect(await screen.findByText('banana')).toBeInTheDocument();
});

Mocks the entire axios module
Use mockRejectedValue() for simulating errors


3. Using MSW – Mock Service Worker (Recommended for Integration Tests)

Install:

npm install msw --save-dev

Create a Handler:

// handlers.js
import { rest } from 'msw';

export const handlers = [
  rest.get('/api/items', (req, res, ctx) => {
    return res(ctx.status(200), ctx.json(['apple', 'banana']));
  }),
];

Setup Server in Test:

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

const server = setupServer(...handlers);

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

Works at the network level β€” no need to mock fetch or axios directly
Ideal for full test coverage of REST APIs


4. Simulating Error States

Jest Example:

fetch.mockImplementationOnce(() =>
  Promise.reject(new Error('API error'))
);

MSW Example:

rest.get('/api/items', (req, res, ctx) => {
  return res(ctx.status(500));
});

Test error boundaries, fallback UIs, and retry logic


Best Practices

Use jest.fn() for simple unit tests
Use msw for integration/end-to-end behavior
Always reset or restore mocks to avoid test pollution
Mock both success and failure cases
Assert against user-visible output, not internal state


Summary – Recap & Next Steps

Mocking APIs is critical for writing fast, reliable, and isolated React tests. Whether you’re unit testing with jest.fn() or doing full integration with MSW, mocking helps control every aspect of your component’s data interaction.

Key Takeaways:

  • Use jest.fn() or mockResolvedValue() to fake APIs
  • Use MSW for network-level, behavior-first mocking
  • Test both loading, success, and failure states
  • Always restore/reset mocks between tests
  • Focus on testing user-facing behavior

Real-World Relevance:
Used in apps like GitHub, Vercel, and Shopify to reliably test everything from form submissions to REST APIsβ€”without depending on live servers.


FAQ Section

Should I use jest.fn() or MSW?
Use jest.fn() for unit tests. Use MSW for integration or behavior-driven tests.


How do I test API failures?
Use mockRejectedValue() (Jest) or return ctx.status(500) (MSW) to simulate errors.


Can I mock GraphQL APIs with MSW?
Yes! MSW supports GraphQL with graphql.query() and graphql.mutation() handlers.


Should I test loading states too?
Absolutely. Mock slow responses or use manual loading triggers and assert loading spinners or skeletons.


Do I need to reset mocks?
Yes. Always use afterEach(() => jest.resetAllMocks()) or reset handlers in MSW to avoid test cross-contamination.


Share Now :
Share

πŸ§ͺ React Mocking APIs in Tests

Or Copy Link

CONTENTS
Scroll to Top