React Test Renderer

19.2.5 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates rendering a React component with `react-test-renderer`, performing a snapshot test, and updating state within an `act` block.

import renderer, { act } from 'react-test-renderer';
import React from 'react';

interface MyComponentProps { message: string; }

const MyComponent: React.FC<MyComponentProps> = ({ message }) => {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    const timer = setTimeout(() => setCount(c => c + 1), 50);
    return () => clearTimeout(timer);
  }, []);
  return (
    <div>
      <h1>{message}</h1>
      <p>Count: {count}</p>
    </div>
  );
};

describe('MyComponent snapshot tests', () => {
  it('renders correctly', () => {
    let tree;
    act(() => {
      tree = renderer.create(<MyComponent message="Hello World" />);
    });
    expect(tree?.toJSON()).toMatchSnapshot();
  });

  it('updates count after a short delay', async () => {
    let tree: renderer.ReactTestRenderer | undefined;
    act(() => {
      tree = renderer.create(<MyComponent message="Test Update" />);
    });
    
    // Wait for the effect to run and update state
    await act(async () => {
      await new Promise(resolve => setTimeout(resolve, 100)); // Simulate async update
    });
    
    expect(tree?.toJSON()).toMatchSnapshot();
    const pElement = tree?.root.findByType('p');
    expect(pElement?.children).toEqual(['Count: ', '1']);
  });
});

view raw JSON →