Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I mock a fetch request in Jest when testing async functions in JavaScript?
Asked on Dec 19, 2025
Answer
To mock a fetch request in Jest for testing async functions, you can use Jest's built-in mocking capabilities. This allows you to simulate the behavior of the fetch API and test how your code handles the response.
<!-- BEGIN COPY / PASTE -->
// Example async function using fetch
async function fetchData(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}
// Jest test case
test('fetchData returns data from API', async () => {
// Mock the fetch function
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ key: 'value' }),
})
);
const data = await fetchData('https://api.example.com/data');
expect(data).toEqual({ key: 'value' });
// Ensure fetch was called with the correct URL
expect(global.fetch).toHaveBeenCalledWith('https://api.example.com/data');
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The `fetchData` function is an example of an async function that uses fetch.
- In the Jest test case, `global.fetch` is mocked to return a resolved promise with a JSON object.
- The `expect` statements verify that the data returned by `fetchData` matches the mock data and that fetch was called with the correct URL.
- This approach allows you to test how your code handles fetch responses without making actual network requests.
Recommended Links:
