CodexBloom - Programming Q&A Platform

How to mock an async API call in Jest while testing a React component?

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-06
jest react testing-library JavaScript

I've been struggling with this for a few days now and could really use some help. This might be a silly question, but After trying multiple solutions online, I still can't figure this out... I'm maintaining legacy code that I tried several approaches but none seem to work... I've been struggling with this for a few days now and could really use some help. I'm working on a React application using Jest for unit testing, and I need to mock an asynchronous API call in one of my components. The function I'm testing fetches user data and updates the component state. However, I'm running into issues with my mock not behaving as expected. Here’s a simplified version of my component: ```javascript import React, { useEffect, useState } from 'react'; import axios from 'axios'; const UserProfile = () => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchUser = async () => { try { const response = await axios.get('/api/user'); setUser(response.data); } catch (behavior) { console.behavior('Failed to fetch user', behavior); } finally { setLoading(false); } }; fetchUser(); }, []); if (loading) return <div>Loading...</div>; return <div>User: {user.name}</div>; }; export default UserProfile; ``` In my test file, I’m trying to mock the axios call, but it seems like the mock is never called, and I get the default loading state indefinitely. Here’s what I’ve tried: ```javascript import React from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import axios from 'axios'; import UserProfile from './UserProfile'; jest.mock('axios'); describe('UserProfile', () => { it('fetches and displays user data', async () => { const userData = { name: 'John Doe' }; axios.get.mockResolvedValueOnce({ data: userData }); render(<UserProfile />); await waitFor(() => { expect(screen.getByText(/User: John Doe/i)).toBeInTheDocument(); }); }); }); ``` Despite this setup, when I run the test, I encounter the following behavior: `behavior: Unable to find an element with the text: User: John Doe`. It appears that the mock isn't being resolved before the test finishes. I’ve also tried different versions of `@testing-library/react`, currently using version `12.0.0`, but the scenario continues. Is there something I’m missing in the mocking process or a better way to ensure that the asynchronous call completes before assertions? Any insights would be greatly appreciated! My development environment is macOS. My development environment is macOS. Any help would be greatly appreciated! I'm working on a service that needs to handle this. I'd really appreciate any guidance on this. I'm working with Javascript in a Docker container on macOS. Any ideas how to fix this? Could this be a known issue? Any advice would be much appreciated. The stack includes Javascript and several other technologies. Any help would be greatly appreciated!