How you would Test a Component that relies on props passed from its parent component?

How you would Test a Component that relies on props passed from its parent component?
October 05, 2024

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:

  1. 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.
  2. 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.
  3. Notification System: A component that shows notifications might rely on a message prop. Tests check if the notifications appear with the right text.
  4. 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.


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates