CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-test-renderer

Deprecated React renderer for creating pure JavaScript object representations of React component trees for testing purposes

Pending
Overview
Eval results
Files

test-renderer.mddocs/

Test Renderer Creation

Core functionality for creating test renderer instances and managing their lifecycle. This is the primary entry point for all react-test-renderer functionality.

Capabilities

Create Function

Creates a test renderer instance for a React element.

/**
 * Creates a test renderer instance for a React element
 * @param element - React element to render
 * @param options - Optional configuration for rendering behavior
 * @returns TestRenderer instance with methods for inspection and manipulation
 */
function create(
  element: React.ReactElement<any>,
  options?: TestRendererOptions
): TestRenderer;

interface TestRendererOptions {
  /** Function to create mock DOM nodes for host components */
  createNodeMock?: (element: React.ReactElement<any>) => any;
  /** Enable concurrent rendering features (deprecated option) */
  unstable_isConcurrent?: boolean;
  /** Enable strict mode for additional checks */
  unstable_strictMode?: boolean;
}

Usage Examples:

import React from 'react';
import { create } from 'react-test-renderer';

// Basic usage
const component = create(<button>Click me</button>);

// With options
const componentWithMocks = create(
  <input type="text" />,
  {
    createNodeMock: (element) => {
      if (element.type === 'input') {
        return {
          focus: jest.fn(),
          blur: jest.fn()
        };
      }
      return null;
    }
  }
);

// With strict mode
const strictComponent = create(
  <MyComponent />,
  { unstable_strictMode: true }
);

TestRenderer Instance

The object returned by create() with methods for interacting with the rendered tree.

interface TestRenderer {
  /** Converts the rendered tree to a JSON representation for snapshot testing */
  toJSON(): ReactTestRendererNode | Array<ReactTestRendererNode> | null;
  /** Returns the internal tree representation (for advanced usage) */
  toTree(): any;
  /** Re-renders the tree with a new element */
  update(element: React.ReactElement<any>): void;
  /** Unmounts the rendered tree and cleans up resources */
  unmount(): void;
  /** Gets the root component instance */
  getInstance(): React.Component<any, any> | any | null;
  /** Root test instance for tree traversal and searching */
  readonly root: ReactTestInstance;
  /** Synchronously flush any pending updates */
  unstable_flushSync: (fn: () => void) => void;
}

toJSON Method

Serializes the rendered tree to a JSON representation suitable for snapshot testing.

/**
 * Converts the rendered tree to a JSON representation
 * @returns JSON object, array of objects, or null for empty trees
 */
toJSON(): ReactTestRendererNode | Array<ReactTestRendererNode> | null;

Usage Examples:

const component = create(
  <div className="container">
    <span>Hello</span>
    <span>World</span>
  </div>
);

const json = component.toJSON();
console.log(json);
// {
//   type: 'div',
//   props: { className: 'container' },
//   children: [
//     { type: 'span', props: {}, children: ['Hello'] },
//     { type: 'span', props: {}, children: ['World'] }
//   ]
// }

// Empty component returns null
const empty = create(null);
console.log(empty.toJSON()); // null

// Multiple root elements return array
const multiple = create([<div key="1">First</div>, <div key="2">Second</div>]);
console.log(multiple.toJSON()); // Array of two objects

toTree Method

Returns the internal tree representation (mainly for advanced debugging).

/**
 * Returns the internal tree representation
 * @returns Internal tree structure (implementation details may change)
 */
toTree(): any;

update Method

Re-renders the tree with a new element, useful for testing component updates.

/**
 * Re-renders the tree with a new element
 * @param element - New React element to render
 */
update(element: React.ReactElement<any>): void;

Usage Examples:

const component = create(<Counter count={0} />);

// Update with new props
component.update(<Counter count={5} />);

// Verify the update
expect(component.toJSON()).toMatchSnapshot();

unmount Method

Unmounts the rendered tree and cleans up resources.

/**
 * Unmounts the rendered tree and cleans up resources
 */
unmount(): void;

getInstance Method

Gets the root component instance for class components.

/**
 * Gets the root component instance
 * @returns Component instance for class components, null for function components
 */
getInstance(): React.Component<any, any> | any | null;

Usage Examples:

class MyComponent extends React.Component {
  myMethod() {
    return 'test';
  }
  
  render() {
    return <div>Component</div>;
  }
}

const component = create(<MyComponent />);
const instance = component.getInstance();
console.log(instance.myMethod()); // 'test'

// Function components return null
const funcComponent = create(<div>Function component</div>);
console.log(funcComponent.getInstance()); // null

unstable_flushSync Method

Synchronously flushes any pending updates (for advanced testing scenarios).

/**
 * Synchronously flush any pending updates
 * @param fn - Function to execute before flushing
 */
unstable_flushSync: (fn: () => void) => void;

Utility Functions

act Function

Utility function for wrapping code that triggers React updates, ensuring proper batching and timing.

/**
 * Wraps code that triggers React updates for proper testing
 * @param callback - Function that triggers updates
 * @returns Promise that resolves when updates complete
 */
function act(callback: () => void | Promise<void>): Promise<void>;

Usage Examples:

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

let component;
await act(async () => {
  component = create(<AsyncComponent />);
});

// Make assertions after act completes
expect(component.toJSON()).toMatchSnapshot();

// For updates
await act(async () => {
  component.update(<AsyncComponent newProp="value" />);
});

unstable_batchedUpdates Function

Batches multiple updates together for performance.

/**
 * Batches multiple updates together
 * @param callback - Function that performs updates
 * @returns Return value of the callback
 */
function unstable_batchedUpdates<T>(callback: () => T): T;

Constants

version

React version string.

/**
 * React version string
 */
const version: string;

_Scheduler

Internal scheduler object (for React team usage, not recommended for public use).

/**
 * Internal scheduler object (unstable, for React team usage)
 */
const _Scheduler: any;

Install with Tessl CLI

npx tessl i tessl/npm-react-test-renderer

docs

index.md

test-renderer.md

tree-traversal.md

tile.json