Testing components that utilize context in React can be challenging, but it is essential for ensuring that your components behave as expected. Context provides a way to pass data through the component tree without having to pass props down manually at every level. When testing such components, you need to ensure that the context is properly set up and that the components respond correctly to the context values.
There are several approaches to testing components that use context, and the choice of method often depends on the testing library you are using. Below, I will outline best practices, practical examples, and common mistakes to avoid when testing these components.
Let's say we have a simple context for user authentication:
import React, { createContext, useContext } from 'react';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = React.useState(null);
return (
{children}
);
};
export const useAuth = () => useContext(AuthContext);
Now, consider a component that displays user information:
const UserProfile = () => {
const { user } = useAuth();
return {user ? `Welcome, ${user.name}` : 'Please log in'};
};
To test this component, we can create a test file:
import { render } from '@testing-library/react';
import { AuthProvider } from './AuthContext';
import UserProfile from './UserProfile';
test('displays welcome message when user is logged in', () => {
const mockUser = { name: 'John Doe' };
const { getByText } = render(
);
// Set user in context
act(() => {
setUser(mockUser);
});
expect(getByText(/Welcome, John Doe/i)).toBeInTheDocument();
});
test('prompts to log in when user is not logged in', () => {
const { getByText } = render(
);
expect(getByText(/Please log in/i)).toBeInTheDocument();
});
By following these best practices and avoiding common pitfalls, you can effectively test components that use context, ensuring they function correctly under various scenarios.