MENU
Test Renderer
This package provides a React renderer that can be used to render React components to pure JavaScript objects, making it easy to grab a snapshot of the platform view hierarchy (like a DOM tree) without using a browser or jsdom. It's a lower-level tool than React Testing Library, which most projects reach for first; react-test-renderer is still useful for library authors and for tests that need direct access to the rendered element tree rather than real DOM nodes.
import TestRenderer from 'react-test-renderer';
function Link(props) {
return <a href={props.page}>{props.children}</a>;
}
const testRenderer = TestRenderer.create(
<Link page="https://www.facebook.com/">Facebook</Link>
);
console.log(testRenderer.toJSON());
// { type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ] }import TestRenderer from 'react-test-renderer';
function MyComponent() {
return (
<div>
<SubComponent foo="bar" />
<p className="my">Hello</p>
</div>
);
}
function SubComponent() {
return (
<p className="sub">Sub</p>
);
}
const testRenderer = TestRenderer.create(<MyComponent />);
const testInstance = testRenderer.root;
expect(testInstance.findByType(SubComponent).props.foo).toBe('bar');
expect(testInstance.findByProps({className: "sub"}).children).toEqual(['Sub']);import {create, act} from 'react-test-renderer';
import App from './app.js'; // The component being tested
// Render the component
let root;
act(() => {
root = create(<App value={1} />);
});
// Make assertions on root
expect(root.toJSON()).toMatchSnapshot();
// Update with some different props
act(() => {
root.update(<App value={2} />);
});
// Make assertions on root
expect(root.toJSON()).toMatchSnapshot();import { useEffect, useRef } from 'react';
import TestRenderer from 'react-test-renderer';
function MyComponent() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input type="text" ref={inputRef} />;
}
let focused = false;
TestRenderer.create(<MyComponent />, {
createNodeMock: (element) => {
if (element.type === 'input') {
// mock a focus function
return {
focus: () => {
focused = true;
},
};
}
return null;
},
});
expect(focused).toBe(true);APIs:
TestRenderer
TestRenderer.create()
TestRenderer.act()
TestRenderer instance
testRenderer.toJSON()
testRenderer.toTree()
testRenderer.update()
testRenderer.unmount()
testRenderer.getInstance()
testRenderer.root
TestInstance
testInstance.find()
testInstance.findByType()
testInstance.findByProps()
testInstance.findAll()
testInstance.findAllByType()
testInstance.findAllByProps()
testInstance.instance
testInstance.type
testInstance.props
testInstance.parent
testInstance.children