When testing a React component that relies on props from its parent component, you want to ensure it behaves correctly based on the props it receives. There's no need to focus on how the parent component works; just make sure the component under test functions as expected.
A good way to start is by using testing tools like Jest and React Testing Library. They help simulate how the component acts in a real environment.
First, think about the props that component expects. Let's say we have a component Greeting
that takes a name
prop and displays a greeting message.
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
To test it, you’d write a test that renders this component with different name values. Use React Testing Library to render the component and check if the correct output is displayed.
import { render, screen } from '@testing-library/react';
import Greeting from './Greeting';
test('displays the correct greeting message', () => {
render(<Greeting name="John" />);
const greetingElement = screen.getByText(/Hello, John!/i);
expect(greetingElement).toBeInTheDocument();
});
// Test for different name
test('handles a different name correctly', () => {
render(<Greeting name="Jane" />);
const greetingElement = screen.getByText(/Hello, Jane!/i);
expect(greetingElement).toBeInTheDocument();
});
This test checks if the Greeting component displays the correct message depending on the name prop.
It is Used for:
- User Profile Display: Components in dashboard applications often need to display user details like name and email. Testing ensures the profile displays correctly when provided specific user data.
- E-commerce Product Page: Product components rely on product information props like name, price, and description. Testing ensures each product displays accurate details that match what the parent passes.
- Notification System: A component that shows notifications might rely on a message prop. Tests check if the notifications appear with the right text.
- Form Components: A form input component might take props like label or placeholder text. Testing ensures that these appear correctly and react to user input as expected.
Overall, testing with props focuses on whether the component does the right thing with the data it gets.