Jest Mock Fetch Not Working Fix
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.fetchinbeforeEachand clean up inafterEach - Use
mockResolvedValuefor successful responses - Use
mockRejectedValuefor error scenarios - Mock the
json()method on the response object - Consider using
jest-fetch-mockpackage for advanced scenarios
Common Mistakes with mock fetch
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro