React Testing Library: How to properly mock a custom hook that uses context?
After trying multiple solutions online, I still can't figure this out... I'm wondering if anyone has experience with I'm currently working with an scenario with testing a custom React hook that consumes context using React Testing Library... The hook, `useUser`, fetches user data from a context provider, and I'd like to write a test for a component that uses this hook. However, I'm struggling to figure out how to properly mock the context for my tests. Hereโs a simplified version of my hook and context: ```javascript import React, { createContext, useContext, useState, useEffect } from 'react'; const UserContext = createContext(); export const UserProvider = ({ children }) => { const [user, setUser] = useState(null); useEffect(() => { // Simulate fetching user data setUser({ name: 'John Doe', age: 30 }); }, []); return <UserContext.Provider value={user}>{children}</UserContext.Provider>; }; export const useUser = () => useContext(UserContext); ``` And hereโs a component that uses this hook: ```javascript const UserProfile = () => { const user = useUser(); return <div>{user ? `Hello, ${user.name}` : 'Loading...'}</div>; }; ``` In my test file, I'm trying to mock the context provider, but I keep getting `TypeError: want to read property 'name' of null` when rendering the `UserProfile` component. Hereโs what I have tried: ```javascript import { render } from '@testing-library/react'; import { UserProvider } from '../path/to/UserProvider'; import UserProfile from '../path/to/UserProfile'; test('renders user name when user is available', () => { const { getByText } = render( <UserProvider> <UserProfile /> </UserProvider> ); expect(getByText(/Loading/i)).toBeInTheDocument(); }); ``` I thought that wrapping `UserProfile` with `UserProvider` would provide the context properly, but the `TypeError` still occurs, and I don't see the user name rendered at all. Could someone guide to understand how to correctly mock the context in my tests so that the `UserProfile` component can access the user data without errors? I'm using React 17.0.2 and React Testing Library 12.1.2. My development environment is Ubuntu. Has anyone else encountered this? For reference, this is a production REST API. Is there a better approach? I'm on Ubuntu 20.04 using the latest version of Javascript. Cheers for any assistance!