{"id":11880,"library":"react-test-renderer","title":"React Test Renderer","description":"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.","status":"active","version":"19.2.5","language":"javascript","source_language":"en","source_url":"https://github.com/facebook/react","tags":["javascript","react","react-native","react-testing"],"install":[{"cmd":"npm install react-test-renderer","lang":"bash","label":"npm"},{"cmd":"yarn add react-test-renderer","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-test-renderer","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for rendering React components.","package":"react","optional":false}],"imports":[{"note":"The 'create' function is the default export, typically aliased or accessed via the default import.","wrong":"import { create } from 'react-test-renderer';","symbol":"create","correct":"import renderer from 'react-test-renderer';\nconst tree = renderer.create(<MyComponent />);"},{"note":"The 'act' utility is a named export and essential for ensuring all updates related to component rendering are flushed before assertions, especially in React 18+.","wrong":"import renderer from 'react-test-renderer'; renderer.act(() => {});","symbol":"act","correct":"import { act } from 'react-test-renderer';"},{"note":"This is a type definition for the renderer instance, used for TypeScript type hinting rather than a runtime value.","wrong":"import { ReactTestRenderer } from 'react-test-renderer';","symbol":"ReactTestRenderer","correct":"import type { ReactTestRenderer } from 'react-test-renderer';"}],"quickstart":{"code":"import renderer, { act } from 'react-test-renderer';\nimport React from 'react';\n\ninterface MyComponentProps { message: string; }\n\nconst MyComponent: React.FC<MyComponentProps> = ({ message }) => {\n  const [count, setCount] = React.useState(0);\n  React.useEffect(() => {\n    const timer = setTimeout(() => setCount(c => c + 1), 50);\n    return () => clearTimeout(timer);\n  }, []);\n  return (\n    <div>\n      <h1>{message}</h1>\n      <p>Count: {count}</p>\n    </div>\n  );\n};\n\ndescribe('MyComponent snapshot tests', () => {\n  it('renders correctly', () => {\n    let tree;\n    act(() => {\n      tree = renderer.create(<MyComponent message=\"Hello World\" />);\n    });\n    expect(tree?.toJSON()).toMatchSnapshot();\n  });\n\n  it('updates count after a short delay', async () => {\n    let tree: renderer.ReactTestRenderer | undefined;\n    act(() => {\n      tree = renderer.create(<MyComponent message=\"Test Update\" />);\n    });\n    \n    // Wait for the effect to run and update state\n    await act(async () => {\n      await new Promise(resolve => setTimeout(resolve, 100)); // Simulate async update\n    });\n    \n    expect(tree?.toJSON()).toMatchSnapshot();\n    const pElement = tree?.root.findByType('p');\n    expect(pElement?.children).toEqual(['Count: ', '1']);\n  });\n});","lang":"typescript","description":"Demonstrates rendering a React component with `react-test-renderer`, performing a snapshot test, and updating state within an `act` block."},"warnings":[{"fix":"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(() => { /* ... */ });`.","message":"Upgrading React to version 18 or higher introduces concurrent features that necessitate wrapping all state updates, component lifecycles, and asynchronous code (e.g., `setTimeout`, promises) that lead to component renders within `act()` calls. Failure to do so will result in warnings and potentially unstable tests.","severity":"breaking","affected_versions":">=18.0.0"},{"fix":"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' }))`).","message":"Snapshots can become brittle and lead to frequent test failures if they capture dynamic or non-deterministic data, such as `Date.now()`, unique IDs (UUIDs), or random numbers. This makes snapshots unreliable for detecting *meaningful* UI changes.","severity":"gotcha","affected_versions":">=any"},{"fix":"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.","message":"Directly calling methods like `instance.setState()` or `instance.forceUpdate()` on the `TestRenderer` root or component instances is deprecated in favor of using the `act()` utility to queue and flush updates, especially in React 18+.","severity":"deprecated","affected_versions":">=18.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"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.","cause":"A component's state or props were updated, causing a re-render, but the update code was not enclosed within `act()`, leading to potential race conditions or incorrect test results, especially in React 18+.","error":"Warning: An update to MyComponent inside a test was not wrapped in act(...)."},{"fix":"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()`.","cause":"This typically occurs when `renderer.create(<MyComponent />)` returns `undefined` or `null`, often because the component failed to render or there was an error during rendering, before `toJSON()` could be called.","error":"TypeError: Cannot read properties of undefined (reading 'toJSON')"},{"fix":"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`).","cause":"This error can occur when trying to use `act()` with an unmounted component or an instance that is no longer valid in the React tree. It can also happen if `act` is called on an instance from a different renderer.","error":"Invariant Violation: Could not find an instance for the passed node."}],"ecosystem":"npm"}