Hone logo
Hone
Problems

Mastering React Component Rendering with Jest

This challenge focuses on accurately testing how React components render and display information. Understanding how to simulate component rendering and assert its output is a fundamental skill for building robust and maintainable React applications. This exercise will equip you with the tools to confidently test your UI components.

Problem Description

Your task is to write a Jest test suite for a simple React component. This component takes a name prop and displays a personalized greeting. You need to implement a test that verifies the component renders the correct greeting based on the provided name.

Key Requirements:

  • You will be provided with a React component written in TypeScript.
  • Your goal is to write a Jest test using @testing-library/react to render this component and assert its output.
  • The test should specifically check that the rendered output contains the expected greeting string.

Expected Behavior:

When the Greeting component is rendered with a name prop, the rendered output should include a string that follows the pattern: "Hello, [name]!".

Edge Cases to Consider:

  • What happens if no name prop is provided? (Though for this specific problem, we'll focus on cases where a name is provided).

Examples

Example 1:

Input: A Greeting component defined as:

import React from 'react';

interface GreetingProps {
  name: string;
}

const Greeting: React.FC<GreetingProps> = ({ name }) => {
  return <div>Hello, {name}!</div>;
};

export default Greeting;

Test Scenario: Render the Greeting component with name="Alice".

Output: The rendered component should contain the text "Hello, Alice!".

Explanation: The test renders the Greeting component with the prop name="Alice". It then asserts that the rendered output contains the string "Hello, Alice!".

Example 2:

Input: The same Greeting component as in Example 1.

Test Scenario: Render the Greeting component with name="Bob".

Output: The rendered component should contain the text "Hello, Bob!".

Explanation: Similar to Example 1, the test renders the Greeting component with a different name and verifies the corresponding greeting is displayed.

Constraints

  • The solution must be written in TypeScript.
  • You must use Jest and @testing-library/react for testing.
  • The focus is on rendering the component and asserting its textual content. No complex event handling or state management is required for this specific challenge.

Notes

  • @testing-library/react provides utilities to interact with and query your React components in a way that resembles how users interact with them.
  • The render function from @testing-library/react is your primary tool for rendering components in a test environment.
  • The screen object from @testing-library/react provides convenient ways to query the DOM.
  • Consider using getByText or container.textContent to assert the rendered output.
Loading editor...
typescript