$ npm install test-renderer
A lightweight test renderer for React and a modern replacement for the deprecated React Test Renderer.
This library is used by React Native Testing Library but should work with any React variant.
It uses React Reconciler to build a custom renderer that operates on host elements by default, and provides escape hatches for complex use-cases. Most React Reconciler options are exposed through RootOptions.
For release and compatibility policy, see docs/versioning.md.
yarn add -D test-renderer
import { createRoot } from "test-renderer";
import { act } from "react";
test("renders a component", async () => {
const renderer = createRoot();
// Use `act` in async mode to allow resolving all scheduled React updates
await act(async () => {
renderer.render(<div>Hello!</div>);
});
expect(renderer.container).toMatchInlineSnapshot(`
<>
<div>
Hello!
</div>
</>
`);
});
RootOptions, TestInstance, and QueryOptionsact: resolving promises, fake timers, and avoiding leaked act scopesInstead of producing a DOM tree or a native view hierarchy, the renderer builds an in-memory Test Output Tree:
TestNodes, where each node is either:
TestInstance: represents a host element such as div or Viewstring: represents a text noderoot.container, a TestInstance whose type is an empty stringTestInstance nodes are traversable and queryable; see the TestInstance APICalling toJSON() on a TestInstance produces a JSON Output Tree, a static, plain-object snapshot of the Test Output Tree at that point in time:
JsonNodes, where each node is either:
JsonElement: a plain object with type, props, and childrenstring: a text nodecreateRoot(options?)Creates a new test renderer root instance.
Parameters:
options (optional): Configuration options for the renderer. See RootOptions below.Returns: A Root object with the following properties:
render(element: ReactElement): Renders a React element into the root. Fragments are supported. Non-element root values such as strings or null are not supported. Must be called within act().unmount(): Unmounts the root and cleans up. Must be called within act().container: A TestInstance wrapper that contains the rendered element(s). Use this to query and inspect the rendered tree.Example:
const renderer = createRoot();
await act(async () => {
renderer.render(<div>Hello!</div>);
});
RootOptionsOptional configuration passed to createRoot. Common options:
textComponentTypes / publicTextComponentTypes: Host component types allowed to contain text nodes (useful for simulating React Native's text rendering rules).isStrictMode: Enable React Strict Mode.identifierPrefix: Prefix for IDs generated by useId().onCaughtError / onUncaughtError / onRecoverableError: Error-handling callbacks.The full options table, along with the TestInstance and QueryOptions APIs, is in the API Reference.
MIT
© 2010 - cnpmjs.org x YWFE | Home | YWFE