JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network
Real Questions. Clear Answers.
Ask any question about JavaScript here... and get an instant response.
Q&A Logo Q&A Logo

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:
  • 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.
✅ Answered with JavaScript best practices.
← Back to All Questions

Q&A Network
The Q&A Network
JavaScript
Ask Questions / Get Answers about JavaScript!
HTML
Ask Questions / Get Answers about HTML!
Data Science
Ask Questions / Get Answers about Data Science!
Creative Writing
Ask Questions / Get Answers about Creative Writing!
Quantum
Ask Questions / Get Answers about Quantum Computing!
AI Writing
Ask Questions / Get Answers about AI Writing!
Networking
Ask Questions / Get Answers about Networking!
AI
Ask Questions / Get Answers about AI!
AI Design
Ask Questions / Get Answers about AI Design!
Web Development
Ask Questions / Get Answers about Web Development!
MobileDev
Ask Questions / Get Answers about Mobile Developement!
VR & AR
Ask Questions / Get Answers about VR & AR!
AI Marketing
Ask Questions / Get Answers about AI Marketing!
Photography
Ask Questions / Get Answers about Photography!
Analytics
Ask Questions / Get Answers about Analytics!
AI Ethics
Ask Questions / Get Answers about AI Ethics!
CSS
Ask Questions / Get Answers about CSS!
Web Hosting
Ask Questions / Get Answers about Hosting!
Graphic Design
Ask Questions / Get Answers about Graphic Design!
AI Coding
Ask Questions / Get Answers about AI Coding!
WordPress
Ask Questions / Get Answers about WordPress!
Security
Ask Questions / Get Answers about Website Security!
IoT
Ask Questions / Get Answers about IoT!
Performance
Ask Questions / Get Answers about Web Vitals!
Tailwind
Ask Questions / Get Answers about Tailwind!
AI Images
Ask Questions / Get Answers about AI Images!
SEO
Ask Questions / Get Answers about SEO!
Chatbots
Ask Questions / Get Answers about Chatbots!
Cloud Computing
Ask Questions / Get Answers about Cloud Computing!
Web Languages
Ask Questions / Get Answers about Web Languages!
Robotics
Ask Questions / Get Answers about Robotics!
AI Video
Ask Questions / Get Answers about AI Video!
Film Production
Ask Questions / Get Answers about Film Production!
Bootstrap
Ask Questions / Get Answers about Bootstrap!
Cybersecurity
Ask Questions / Get Answers about Cybersecurity!
AI Business
Ask Questions / Get Answers about AI Business!
AI Education
Ask Questions / Get Answers about AI Education!
Monetization
Ask Questions / Get Answers about Ad & Monetization!
AI Audio
Ask Questions / Get Answers about AI Audio!
DevOps
Ask Questions / Get Answers about DevOps!
Video Editing
Ask Questions / Get Answers about Video Editing!