how to to Mock a Dependency with Jest in a React Component that Uses Context API
I've been banging my head against this for hours... I need help solving I've tried everything I can think of but I'm confused about I need help solving I've been struggling with this for a few days now and could really use some help. I'm stuck on something that should probably be simple. I'm working with an scenario while trying to unit test a React component that uses the Context API with Jest. The component relies on a context provider to fetch user data, and I'm having trouble properly mocking that context during testing. Here's a simplified version of my component: ```javascript import React, { useContext } from 'react'; import { UserContext } from './UserContext'; const UserProfile = () => { const { user } = useContext(UserContext); return <div>{user ? `Hello, ${user.name}` : 'Loading...'}</div>; }; export default UserProfile; ``` In my test file, I'm trying to mock the UserContext like this: ```javascript import { render } from '@testing-library/react'; import UserProfile from './UserProfile'; import { UserContext } from './UserContext'; test('renders loading state', () => { const mockContextValue = { user: null }; const { getByText } = render( <UserContext.Provider value={mockContextValue}> <UserProfile /> </UserContext.Provider> ); expect(getByText(/loading/i)).toBeInTheDocument(); }); test('renders user name when user is available', () => { const mockContextValue = { user: { name: 'John' } }; const { getByText } = render( <UserContext.Provider value={mockContextValue}> <UserProfile /> </UserContext.Provider> ); expect(getByText(/Hello, John/i)).toBeInTheDocument(); }); ``` However, the tests unexpected result with the following behavior: `TypeError: want to read property 'user' of null`. It seems like the context is not being properly mocked. I’ve checked that the UserContext is correctly set up, and I can successfully render the component outside of the tests. I've also tried wrapping my tests in a `beforeEach` block to ensure the context is reset, but that didn't solve the scenario either. Could anyone guide to understand why the mock might not be working as expected? What am I missing here? My development environment is macOS. What am I doing wrong? This is happening in both development and production on Debian. Thanks for any help you can provide! Any ideas how to fix this? This is part of a larger service I'm building.