Last Updated: February 25, 2016
·
1.102K
· radmen

Retrieve React shallow rendered component

React Test Utils allows to make shallow render of a component.

This is very helpful for writing components unit tests.

Unfortunately this solution is very limited.

For example - render() method doesn't return components instance.

It's possible to retrieve it - after render instance of component is stored in _instance._instance attribute of ReactShallowRenderer.

const renderer = TestUtils.createRenderer();
renderer.render(<MyComponent />);

const component = renderer._instance._instance;

Note that this may not work in all situations. My guess (didn't try it) is that this workaround will fail when more elements are rendered (eg. renderer.render(<MyComponent/><div/>).

ShallowRenderer doesn't call componentDidMount or componentWillUnmount methods.

It's possible to call them when component instance is grabbed from the renderer.

If state of the component will change renderer.getRenderOutput() method will include the changes.

const renderer = TestUtils.createRenderer();
renderer.render(<MyComponent />);

const component = renderer._instance._instance;
component.componentDidMount();

component.setState({
  // ...
});

const output = renderer.getRenderOutput();

This should work on React 0.14.

1 Response
Add your response

Must try that tommorow, how it will behave when component is wrapped with High Order Component..

over 1 year ago ·