Testing React Components with React Test Renderer

This post is written about how to test React Components with React Test Renderer v16.

React Test Renderer is a renderer for testing React Components, which traverses a ReactElement tree and represents as a JSON object.

The renderer is combined with Jest’s snapshot testing.

You can use the renderer like this.

React Test Renderer has gotten very useful features at v16. Lets’ see the features!

You can traverse ReactElements with some useful APIs such as find, findByType, findByProps, findAll, findAllByType, findAllByProps. In addition to that, you can rerender with testRenderer.update(<App /) and get the component instance through testRenderer.root.instance, which means you can access many features the instance provides. ( instance.state, instance.props, instance.setState, etc…)

For more details, please check the documentation I wrote.


Mock Ref function for DOMComponent

TestRenderer.create has an option as the 2nd argument. You can pass createNodeMock function as the option. createNodeMock function is called when Ref functions for DOMComponent is called. You can mock the Ref function through this option like this.

The above example, I mock a Ref function for input because the component is calling focus() function in the componentDidMount. createNodeMock functions is called every ref props so I’m checking element.type to only apply the mock behavior to input element.

TestRender or ShallowRenderer?

ShallowRenderer is a very useful renderer to test a component, which renders a component shallowly so you don’t need care about child components’s behavior. In addition to that, enzyme provides ShallowRenderer very useful features.

But ShallowRenderer has some limitations, which are no Ref support and no calling componentDidMount and componentDidUpdate (BTW enzyme supports the lifecycle methods by default in v3).

So if you want to test all components or want to test a component that depends on Ref, TestRender might be good for you. Otherwise enzyme is a still good option for testing a component.

BTW enzyme v3 moves to an adapter architecture so you need to install not only enzyme but also an adapter that depends on React version you use.

import Enzyme from 'enzyme;
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({adapter: new Adapter()});
Show your support

Clapping shows how much you appreciated Toru Kobayashi’s story.