Mocking Fetch and Network Requests
What you'll learn: How to replace fetch with mocks to test network-dependent code without making real HTTP calls.
When your code makes HTTP requests using fetch, you don't want your tests actually hitting real APIs. Real requests are slow, unreliable (networks fail!), expensive (rate limits), and make tests dependent on external services. Instead, you mock fetch to return controlled responses.
Why Mock Network Requests?
Think of it like testing a cashier app: you don't need real credit card transactions to verify the receipt prints correctly. You just need to pretend the payment succeeded and check the output.
Mocking fetch lets you:
- Test success and error paths without real servers
- Control exact response data
- Run tests instantly and offline
- Avoid hitting rate limits or costing money
How It Works
Since fetch is a global function, you can mock it using jest.spyOn(global, 'fetch') to intercept calls. You then define what the mock should return—typically a resolved Promise containing a fake Response object.
// Function to test
async function getUserName(userId) {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data.name;
}
// Test with mocked fetch
test('getUserName returns user name from API', async () => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ name: 'Alice' })
})
);
const name = await getUserName(123);
expect(name).toBe('Alice');
expect(fetch).toHaveBeenCalledWith('/api/users/123');
});
You're replacing the real fetch with a fake one that returns exactly what you need for the test.
Key Takeaway: Mocking fetch with jest.fn() lets you test HTTP-dependent code by simulating API responses without making real network requests, giving you fast, reliable, and controllable tests.