Ask any question about JavaScript here... and get an instant response.
How do I mock a fetch call with Jest to test async functions in JavaScript?
Asked on Dec 09, 2025
Answer
To mock a fetch call with Jest for testing async functions, you can use Jest's built-in mocking capabilities to simulate the fetch API. This allows you to control the responses and test how your code handles them.
<!-- BEGIN COPY / PASTE -->
// Example async function using fetch
async function fetchData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
}
// Jest test with fetch mock
test('fetchData returns data when fetch is successful', async () => {
const mockData = { data: '12345' };
// Mock fetch to resolve with a successful response
global.fetch = jest.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve(mockData),
})
);
const data = await fetchData('https://api.example.com/data');
expect(data).toEqual(mockData);
expect(global.fetch).toHaveBeenCalledWith('https://api.example.com/data');
});
test('fetchData throws an error when fetch fails', async () => {
// Mock fetch to resolve with a failed response
global.fetch = jest.fn(() =>
Promise.resolve({
ok: false,
})
);
await expect(fetchData('https://api.example.com/data')).rejects.toThrow('Network response was not ok');
expect(global.fetch).toHaveBeenCalledWith('https://api.example.com/data');
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "fetchData" function uses the fetch API to retrieve data from a URL and returns the JSON response.
- In the first test, "global.fetch" is mocked to return a successful response with mock data.
- In the second test, "global.fetch" is mocked to simulate a failed fetch response.
- "jest.fn()" is used to create a mock function for "fetch".
- Use "expect(...).toEqual(...)" to check if the returned data matches the mock data.
- Use "expect(...).rejects.toThrow(...)" to test if the function throws an error as expected.
Recommended Links:
