How to Test Loading and Error States :👈 👉:How to Test Components with Asynchronous Data

How to Test Components That Use Context

How to Test Components That Use Context in React

1. What Is Context in React?

React Context allows components to share data without passing props through every intermediate component.

For example, an application may use Context to share:

  • Logged-in user information
  • Authentication status
  • Theme settings
  • Shopping cart data
  • Language preferences
  • Application configuration

A component that uses Context depends on the value supplied by its Context Provider. Therefore, when testing such components, we must provide the required Context Provider.

2. Create a Context

Consider an application that stores logged-in user information using Context.

AuthContext.jsx

import { createContext, useContext } from "react";
export const AuthContext = createContext(null);
export function useAuth() {
    return useContext(AuthContext);
}

3. Create a Component That Uses Context

The following component reads authentication information from AuthContext.

UserProfile.jsx

import { useAuth } from "./AuthContext";
function UserProfile() {
    const { user, logout } = useAuth();
    if (!user) {
        return <p>Please log in</p>;
    }
    return (
        <div>
            <h2>Welcome, {user.name}</h2>
            <button onClick={logout}>
                Logout
            </button>
        </div>
    );
}
export default UserProfile;

The component depends on two Context values:

  • user: Contains the logged-in user's information.
  • logout: Function to log out the user.

4. Why Do We Need a Provider in Tests?

If we render UserProfile without AuthContext.Provider, the component receives the default Context value.

In this example, the default value is null. Destructuring user and logout from null causes an error.

Therefore, the test must provide a valid Context value.

5. Method 1: Wrap the Component with Context Provider

This is the simplest approach.

UserProfile.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import UserProfile from "./UserProfile";
import { AuthContext } from "./AuthContext";
describe("UserProfile", () => {
    it("should display the logged-in user's name", () => {
        const mockContextValue = {
            user: {
                name: "John"
            },
            logout: vi.fn()
        };
        render(
            <AuthContext.Provider value={mockContextValue}>
                <UserProfile />
            </AuthContext.Provider>
        );
        expect(
            screen.getByText("Welcome, John")
        ).toBeInTheDocument();
    });
});

Explanation:

  1. Create a mock Context value.
  2. Provide the mock value through AuthContext.Provider.
  3. Render UserProfile inside the Provider.
  4. Verify that the user's name appears on the screen.

6. Test When the User Is Not Logged In

We should also test different Context states.

import { render, screen } from "@testing-library/react";
import { AuthContext } from "./AuthContext";
import UserProfile from "./UserProfile";
import { vi, expect, it } from "vitest";
it("should display login message when user is not logged in", () => {
    const mockContextValue = {
        user: null,
        logout: vi.fn()
    };
    render(
        <AuthContext.Provider value={mockContextValue}>
            <UserProfile />
        </AuthContext.Provider>
    );
    expect(
        screen.getByText("Please log in")
    ).toBeInTheDocument();
});

This verifies that the component correctly handles an unauthenticated user.

7. Test Context-Based Button Actions

Context may provide functions that components call when users interact with the UI.

For example, UserProfile calls logout when the Logout button is clicked.

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { AuthContext } from "./AuthContext";
import UserProfile from "./UserProfile";
import { vi, expect, it } from "vitest";
it("should call logout when the button is clicked", async () => {
    const user = userEvent.setup();
    const mockLogout = vi.fn();
    const mockContextValue = {
        user: {
            name: "John"
        },
        logout: mockLogout
    };
    render(
        <AuthContext.Provider value={mockContextValue}>
            <UserProfile />
        </AuthContext.Provider>
    );
    await user.click(
        screen.getByRole("button", { name: "Logout" })
    );
    expect(mockLogout).toHaveBeenCalledTimes(1);
});

What are we testing?

  • The Logout button is displayed.
  • The user clicks the button.
  • The logout function supplied through Context is called exactly once.

8. Method 2: Create a Reusable Custom Render Function

When many components depend on the same Context Provider, wrapping every component manually creates repetitive test code.

A better approach is to create a reusable custom render function.

test-utils.jsx

import { render } from "@testing-library/react";
import { AuthContext } from "./AuthContext";
export function renderWithAuth(
    ui,
    {
        providerProps = {},
        ...renderOptions
    } = {}
) {
    const defaultValue = {
        user: {
            name: "John"
        },
        logout: () => {}
    };
    const value = {
        ...defaultValue,
        ...providerProps
    };
    function Wrapper({ children }) {
        return (
            <AuthContext.Provider value={value}>
                {children}
            </AuthContext.Provider>
        );
    }
    return render(ui, {
        wrapper: Wrapper,
        ...renderOptions
    });
}

Now we can reuse this function in multiple test files.

UserProfile.test.jsx

import { screen } from "@testing-library/react";
import { expect, it } from "vitest";
import UserProfile from "./UserProfile";
import { renderWithAuth } from "./test-utils";
it("should display the user name", () => {
    renderWithAuth(<UserProfile />);
    expect(
        screen.getByText("Welcome, John")
    ).toBeInTheDocument();
});
it("should display login message for unauthenticated users", () => {
    renderWithAuth(
        <UserProfile />,
        {
            providerProps: {
                user: null
            }
        }
    );
    expect(
        screen.getByText("Please log in")
    ).toBeInTheDocument();
});

Benefits:

  • Avoids repetitive Provider code.
  • Makes test files shorter.
  • Provides common default Context values.
  • Allows individual tests to override Context values.

9. Method 3: Test Components Using Multiple Context Providers

Real-world applications often use multiple Context Providers.

For example:

  • AuthContext for authentication.
  • ThemeContext for theme settings.
  • CartContext for shopping cart information.

A component may consume all three Contexts.

ThemeContext.jsx

import { createContext, useContext } from "react";
export const ThemeContext = createContext("light");
export function useTheme() {
    return useContext(ThemeContext);
}

Dashboard.jsx

import { useAuth } from "./AuthContext";
import { useTheme } from "./ThemeContext";
function Dashboard() {
    const { user } = useAuth();
    const theme = useTheme();
    return (
        <div>
            <h2>Welcome, {user.name}</h2>
            <p>Current theme: {theme}</p>
        </div>
    );
}
export default Dashboard;

Dashboard.test.jsx

import { render, screen } from "@testing-library/react";
import { AuthContext } from "./AuthContext";
import { ThemeContext } from "./ThemeContext";
import Dashboard from "./Dashboard";
it("should display values from multiple Contexts", () => {
    const authValue = {
        user: {
            name: "John"
        },
        logout: () => {}
    };
    render(
        <AuthContext.Provider value={authValue}>
            <ThemeContext.Provider value="dark">
                <Dashboard />
            </ThemeContext.Provider>
        </AuthContext.Provider>
    );
    expect(
        screen.getByText("Welcome, John")
    ).toBeInTheDocument();
    expect(
        screen.getByText("Current theme: dark")
    ).toBeInTheDocument();
});

Important: Nest all the required Providers around the component being tested.

10. Test Context Updates

Context values can change when application state changes. We should verify that the component displays the updated value.

CounterContext.jsx

import { createContext, useContext, useState } from "react";
export const CounterContext = createContext(null);
export function CounterProvider({ children }) {
    const [count, setCount] = useState(0);
    return (
        <CounterContext.Provider value={{ count, setCount }}>
            {children}
        </CounterContext.Provider>
    );
}
export function useCounter() {
    return useContext(CounterContext);
}

CounterDisplay.jsx

import { useCounter } from "./CounterContext";
function CounterDisplay() {
    const { count, setCount } = useCounter();
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>
                Increment
            </button>
        </div>
    );
}
export default CounterDisplay;

CounterDisplay.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { CounterProvider } from "./CounterContext";
import CounterDisplay from "./CounterDisplay";
it("should update the component when Context value changes", async () => {
    const user = userEvent.setup();
    render(
        <CounterProvider>
            <CounterDisplay />
        </CounterProvider>
    );
    expect(
        screen.getByText("Count: 0")
    ).toBeInTheDocument();
    await user.click(
        screen.getByRole("button", { name: "Increment" })
    );
    expect(
        screen.getByText("Count: 1")
    ).toBeInTheDocument();
});

What does this test verify?

  1. The initial Context value is zero.
  2. The user clicks Increment.
  3. The Provider updates its state.
  4. React propagates the new Context value.
  5. The consuming component displays the updated count.

11. Should We Mock Context or Use the Real Provider?

Both approaches are useful, depending on what we want to test.

Approach When to Use
Mock Context value Testing a component's rendering and behavior with specific Context values.
Real Context Provider Testing Provider state, update logic and integration with consumers.
Reusable custom render Testing many components that use the same Provider.
Multiple Providers Testing components that depend on multiple Contexts.

Recommended approach: Use mock Context values when testing an individual component. Use the real Provider when testing how Context state and its consumers work together.

12. Common Mistakes While Testing Context

1. Forgetting the Provider

Incorrect:

render(<UserProfile />);

Correct:

render(
    <AuthContext.Provider value={mockContextValue}>
        <UserProfile />
    </AuthContext.Provider>
);

2. Providing an Incorrect Context Value

If the component expects user and logout properties, provide both with the correct types. Do not provide an unrelated object or omit required properties.

3. Mocking Context When Provider Logic Needs Testing

If the purpose is to test whether the Provider correctly updates state, use the actual Provider rather than replacing its behavior with a mock value.

4. Testing Internal Context Implementation Instead of UI Behavior

Prefer checking what users see and do rather than inspecting internal React state.

5. Forgetting Asynchronous User Interactions

Use await with user-event operations such as user.click() before checking the resulting UI.

13. Best Practices

  • Always provide the Context required by the component.
  • Create reusable render helpers for commonly used Providers.
  • Use realistic Context values.
  • Test authenticated and unauthenticated states.
  • Test functions supplied through Context.
  • Test Context updates using the real Provider.
  • Use multiple Providers when the component depends on multiple Contexts.
  • Prefer React Testing Library queries such as getByRole() and getByText().
  • Avoid testing Context implementation details.
  • Keep tests independent of one another.

14. Interview Questions and Answers

Q1. How do you test a React component that uses Context?

Render the component inside the required Context Provider and pass a suitable test value.

Q2. Why does a component fail when tested without its Provider?

It receives the default Context value. If the component expects properties or functions that are missing from that value, it may throw an error.

Q3. What is a custom render function in React Testing Library?

It is a reusable function that wraps components with common Providers before rendering them. It reduces repetitive test code.

Q4. Should we mock Context or use the actual Provider?

Mock Context values for isolated component tests. Use the actual Provider when testing Context state updates and integration behavior.

Q5. How do you test multiple Context Providers?

Nest all required Providers around the component and provide suitable values to each Provider.

Q6. How do you test Context updates?

Render the component with the actual Provider, perform an action that changes Provider state, and verify the updated UI.

Q7. Can we test a custom hook that uses Context?

Yes. Use renderHook() with a wrapper that supplies the required Provider.

Example:

import { renderHook } from "@testing-library/react";
import { AuthContext, useAuth } from "./AuthContext";
it("should read the user from Context", () => {
    const value = {
        user: {
            name: "John"
        },
        logout: () => {}
    };
    const wrapper = ({ children }) => (
        <AuthContext.Provider value={value}>
            {children}
        </AuthContext.Provider>
    );
    const { result } = renderHook(
        () => useAuth(),
        { wrapper }
    );
    expect(result.current.user.name).toBe("John");
});

15. Key Takeaway

Testing components that use Context is straightforward:

  1. Identify which Context the component consumes.
  2. Wrap the component with the required Provider.
  3. Supply mock values or use the real Provider.
  4. Test what the user sees and how the component responds to interactions.
  5. Use reusable custom render functions when multiple tests need the same Providers.

Remember: The goal is to test the component's user-visible behavior while providing the Context dependencies it needs.

🔙
How to Test Loading and Error States :👈 👉:How to Test Components with Asynchronous Data

Comments and Discussion