CodexBloom - Programming Q&A Platform

implementing Mocking a Third-Party API Call in React Testing Library

πŸ‘€ Views: 1900 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-08
react jest testing-library JavaScript

I've been banging my head against this for hours... Quick question that's been bugging me - Quick question that's been bugging me - I'm working with scenarios while trying to mock a third-party API call in my React component tests using React Testing Library. My component makes a fetch request to an external service to retrieve user data, but when I try to write a unit test for it, the API call is not being mocked correctly, resulting in network errors. Here's a simplified version of my component: ```javascript import React, { useEffect, useState } from 'react'; const UserProfile = () => { const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { const response = await fetch('https://api.example.com/user'); const data = await response.json(); setUser(data); }; fetchUser(); }, []); if (!user) return <div>Loading...</div>; return <div>{user.name}</div>; }; export default UserProfile; ``` In my test file, I've tried using `jest.mock` to mock the fetch call, but it seems like the component is not using the mocked version. Here’s how I set up my test: ```javascript import { render, screen } from '@testing-library/react'; import UserProfile from './UserProfile'; beforeEach(() => { global.fetch = jest.fn(); }); afterEach(() => { jest.restoreAllMocks(); }); test('renders user name after fetching', async () => { const mockUser = { name: 'John Doe' }; fetch.mockResolvedValueOnce({ json: jest.fn().mockResolvedValueOnce(mockUser) }); render(<UserProfile />); expect(await screen.findByText('John Doe')).toBeInTheDocument(); }); ``` However, when I run this test, I get the following behavior: `TypeError: want to read properties of undefined (reading 'then')`. I've checked that `fetch` is being called and mocked correctly, yet the component still throws this behavior. I've also verified that my test setup is working by creating a very basic mock of the fetch function, but it seems like the scenario lies with the way I'm resolving the promise in the mock. Any suggestions on how to properly mock my API call or handle this situation would be greatly appreciated! How would you solve this? This is part of a larger application I'm building. I appreciate any insights!