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.


RESETRUNFULL
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' ] }

RESETRUNFULL
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']);

RESETRUNFULL
import {create, act} from 'react-test-renderer';import App from './app.js'; // The component being tested// render the componentlet root; act(() => {
  root = create(<App value={1}/>)});// make assertions on root expect(root.toJSON()).toMatchSnapshot();// update with some different propsact(() => {
  root.update(<App value={2}/>);})// make assertions on root expect(root.toJSON()).toMatchSnapshot();

RESETRUNFULL
import TestRenderer from 'react-test-renderer';class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.input = null;
  }
  componentDidMount() {
    this.input.focus();
  }
  render() {
    return <input type="text" ref={el => this.input = el} />
  }}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: APIs: 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