πŸ§ͺ React Testing & Debugging
Estimated reading: 3 minutes 31 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ§ͺ React Mocking APIs in Tests

Or Copy Link

CONTENTS
Scroll to Top