Hone logo
Hone
Problems

Testing React's useState Hook with Jest

This challenge focuses on writing effective unit tests for React components that utilize the useState hook. Understanding how to test state changes is fundamental to ensuring your React applications behave as expected and to catch regressions.

Problem Description

Your task is to create a unit test for a simple React component using Jest. This component will manage a counter state using the useState hook. The test should verify that the initial state is set correctly and that updating the state through a button click also works as intended.

Key Requirements:

  • Create a test file for a React component named Counter.
  • The Counter component should have a button that, when clicked, increments a counter value managed by useState.
  • The test should assert that the initial counter value displayed is 0.
  • The test should simulate a click on the button and assert that the counter value updates to 1.
  • Use the @testing-library/react library for rendering and interacting with the component.

Expected Behavior:

  • When the Counter component is rendered, it should display "Count: 0".
  • When the "Increment" button is clicked, the displayed text should update to "Count: 1".

Edge Cases to Consider:

  • (For this specific problem, the primary focus is on the basic increment, so explicit edge cases are minimal. However, in more complex scenarios, consider testing multiple increments, resetting, or other state interactions.)

Examples

Example 1:

Component Rendered:
<Counter />

Initial Display: "Count: 0"

User Action: Clicks the "Increment" button.

Updated Display: "Count: 1"

Explanation: The useState hook initializes the count to 0. Clicking the button triggers the setCount function, incrementing the state to 1.

Constraints

  • The solution must be written in TypeScript.
  • Jest and @testing-library/react are the required testing tools.
  • Focus on unit testing the component's state management.
  • The component itself should be functional, but the primary deliverable is the test.

Notes

  • You'll need to simulate user interactions like button clicks. @testing-library/react provides helpful utilities for this.
  • Remember to import the necessary functions from React and @testing-library/react.
  • Think about how useState works: it returns an array with the current state value and a function to update it. Your test needs to verify that this update mechanism functions correctly.
Loading editor...
typescript