Hone logo
Hone
Problems

Implementing Change Detection with Jest

Change detection is a crucial aspect of testing user interface components, particularly in frameworks like React, Angular, or Vue. This challenge focuses on implementing a robust change detection mechanism within a Jest testing environment to accurately verify that component state updates trigger expected re-renders and behavior. You'll be provided with a simplified component and tasked with writing Jest tests that utilize a change detection strategy to confirm state modifications.

Problem Description

You are given a simple TypeScript component, Counter, that maintains a count and provides a method to increment it. Your task is to write Jest tests that verify the following:

  1. Initial State: The component renders with the initial count value of 0.
  2. Increment Functionality: Calling the increment method updates the component's state, causing a re-render with the incremented count.
  3. Re-render Verification: The tests should reliably detect and confirm the re-render triggered by the state update. This requires a mechanism to observe and assert the changes in the rendered output.

You will need to use Jest's act function to wrap state updates and ensure that the component has finished rendering before assertions are made. Failure to use act can lead to unreliable test results.

Examples

Example 1:

Input: Counter component with initial count 0.  Increment the count to 1.
Output: The component renders with count 1.
Explanation: The increment function updates the state, triggering a re-render. The test verifies the new count value.

Example 2:

Input: Counter component with initial count 0. Increment the count to 1, then to 2.
Output: The component renders with count 2.
Explanation: Multiple increments should update the state and re-render the component accordingly. The test verifies the final count value.

Example 3: (Edge Case - Initial Render)

Input: Counter component with initial count 0.
Output: The component renders with count 0.
Explanation: This verifies the component renders correctly on its initial mount.

Constraints

  • The component Counter is provided. You are not allowed to modify the component itself.
  • You must use Jest's act function to wrap state updates.
  • Tests should be written in TypeScript.
  • The tests should be reliable and avoid timing issues.
  • The component uses a simple useState hook for state management.

Notes

  • Consider using screen.getByText or similar Jest methods to access and assert the rendered output.
  • The key to this challenge is ensuring that your tests accurately detect and verify the re-render triggered by state updates. Incorrect usage of act is a common pitfall.
  • Think about how to structure your tests to clearly demonstrate the change detection process.
  • Focus on writing clean, readable, and maintainable tests.
Loading editor...
typescript