The `react-test-renderer` package provides a renderer that can be used to render React components into plain JavaScript objects, offering a way to test components without requiring a DOM environment or a browser. It is primarily used for snapshot testing, enabling the generation of serializable JSON representations of a component tree that can be compared against previous snapshots to detect unintended UI changes over time. The current stable version is 19.2.5, aligning with the core React library's frequent patch releases. Unlike `@testing-library/react`, this library focuses on the internal structure and rendered output of components rather than simulating user interactions, making it suitable for asserting on the rendered tree itself.
npm install react-test-rendererVerified import paths — ran on the pinned version, not inferred.
Demonstrates rendering a React component with `react-test-renderer`, performing a snapshot test, and updating state within an `act` block.
Ensure all code that causes a React component to render or update in tests (e.g., `renderer.create`, `instance.update`, event handlers, async operations that resolve) is wrapped in `act(() => { /* ... */ });`.Use jest's `expect.any(String)` or `expect.any(Number)` matchers, or mock modules/functions that generate dynamic data to provide deterministic values (e.g., `jest.mock('uuid', () => ({ v4: () => 'fixed-uuid' }))`).Refactor tests to use `act()` for all component updates. For example, instead of `instance.setState({ value: 'new' })`, wrap the update in `act(() => instance.props.onChange('new'))` or a similar prop-based interaction.Wrap the code block that initiates the update (e.g., `renderer.create`, `instance.update`, `fireEvent`, `setTimeout` callbacks) with `act(() => { ... });` or `await act(async () => { ... });` for async operations.Ensure the component renders without errors. Debug the component's render method or constructor to identify any issues. Also, verify that `tree` is assigned and not `undefined` before calling `tree.toJSON()`.
Ensure that `act` is operating on a currently mounted component instance returned by the `react-test-renderer` `create` function, and that you are not mixing instances from different rendering contexts (e.g., `react-test-renderer` and `react-dom/test-utils`).