Hone logo
Hone
Problems

Testing Chromatic Components with Jest

Chromatic is a tool for visually testing UI components, particularly useful for component libraries like Storybook. This challenge focuses on writing Jest tests to verify the rendering and basic functionality of a simple Chromatic component. You'll be setting up a Jest environment to capture snapshots of your component and ensuring it renders correctly under different props.

Problem Description

You are tasked with creating a Jest test suite for a React component called Greeting. The Greeting component accepts a name prop (string) and a greeting prop (string, defaulting to "Hello"). The component should render a <div> containing the greeting followed by the name. Your goal is to write Jest tests that:

  1. Verify the component renders without errors.
  2. Capture snapshots of the component's rendered output with different prop combinations.
  3. Ensure the component displays the correct greeting and name based on the provided props.

Examples

Example 1:

Input: <Greeting name="World" />
Output: <div>Hello World</div>
Explanation: The component renders with the default greeting "Hello" and the provided name "World".

Example 2:

Input: <Greeting name="Alice" greeting="Hi" />
Output: <div>Hi Alice</div>
Explanation: The component renders with the custom greeting "Hi" and the provided name "Alice".

Example 3: (Edge Case - Empty Name)

Input: <Greeting name="" greeting="Hey" />
Output: <div>Hey</div>
Explanation: The component renders with the custom greeting "Hey" and an empty name.  The empty name should not cause an error, and the component should still render correctly.

Constraints

  • The Greeting component is provided below. Do not modify the component itself.
  • You must use Jest and React Testing Library.
  • Your tests should cover at least three different prop combinations, including the default greeting.
  • All tests must pass without errors and produce valid snapshots.
  • The component should be tested in a src/components/Greeting.test.tsx file.

Notes

  • Consider using render from React Testing Library to render the component.
  • Use expect(tree).toMatchSnapshot() to capture snapshots.
  • Think about how to test the component with different prop values to ensure it behaves as expected.
  • Ensure your test file is correctly configured to import the Greeting component.
  • You'll need to have Jest and React Testing Library installed in your project. If not, install them using npm install --save-dev jest @testing-library/react.
// src/components/Greeting.tsx
import React from 'react';

interface GreetingProps {
  name: string;
  greeting?: string;
}

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

export default Greeting;
Loading editor...
typescript