Skip to content

Jest Mock Fetch Not Working Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Jest Mock Fetch Not Working Fix. We cover key concepts, practical examples, and best practices.

Your test makes a real HTTP request instead of using the mocked fetch — the test fails with a network error or hits a real API endpoint.

The Problem

// WRONG — fetch is not mocked
test('fetches user data', async () => {
  const response = await fetch('/api/user/1');
  const user = await response.json();
  expect(user.name).toBe('Alice');
  // Real network request — slow and flaky!
});
Timeout - Async callback was not invoked within the 5000 ms timeout

The test hits the real network, which is slow, unpredictable, and may not even have the API running.

Step-by-Step Fix

1. Mock global fetch with jest.fn

// RIGHT — mock global fetch
global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ name: 'Alice' }),
  })
);

test('fetches user data', async () => {
  const response = await fetch('/api/user/1');
  const user = await response.json();
  expect(user.name).toBe('Alice');
  expect(fetch).toHaveBeenCalledWith('/api/user/1');
});

2. Use mockReturnValue for cleaner syntax

// RIGHT — cleaner mock setup
beforeEach(() => {
  global.fetch = jest.fn().mockResolvedValue({
    json: jest.fn().mockResolvedValue({ name: 'Alice' }),
  });
});

afterEach(() => {
  delete global.fetch;
});

test('handles successful response', async () => {
  const response = await fetch('/api/user/1');
  const data = await response.json();
  expect(data.name).toBe('Alice');
});

3. Mock different responses per call

// RIGHT — sequence of responses
const mockResponses = [
  { ok: true, json: () => Promise.resolve([{ id: 1 }]) },
  { ok: false, status: 404 },
];

global.fetch = jest.fn()
  .mockResolvedValueOnce(mockResponses[0])
  .mockResolvedValueOnce(mockResponses[1]);

4. Mock fetch with error scenarios

// RIGHT — network error simulation
global.fetch = jest.fn().mockRejectedValue(new Error('Network Error'));

test('handles network failure', async () => {
  await expect(fetch('/api/data')).rejects.toThrow('Network Error');
});

Expected output:

PASS  tests/fetch.test.js
  ✓ fetches user data (10 ms)
  ✓ handles successful response (5 ms)
  ✓ handles network failure (3 ms)

Prevention Tips

  • Mock global.fetch in beforeEach and clean up in afterEach
  • Use mockResolvedValue for successful responses
  • Use mockRejectedValue for error scenarios
  • Mock the json() method on the response object
  • Consider using jest-fetch-mock package for advanced scenarios

Common Mistakes with mock fetch

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world JEST code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### How do I mock fetch headers and status codes?

Return a full response object: { ok: true, status: 200, headers: new Headers({ 'Content-Type': 'application/json' }), json: () => Promise.resolve(data) }. Mock any property your code accesses.

Should I mock fetch or use mock service worker (MSW)?

For most Jest tests, mocking fetch directly is simpler. For integration tests where you want real request matching and responses, MSW is better. Mock fetch for unit tests, use MSW for component and E2E tests.

Does mocking global.fetch affect all tests?

Yes, unless you clean up. Always restore or delete global.fetch in afterEach. Use delete global.fetch or store the original: const originalFetch = global.fetch and restore it afterward.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro