Testing React components using Shallow Rendering
Coding
This is a continuation of Getting started w/ React & Mocha blog post. Here I’ll shortly describe one more alternative how to test a React component.
Set-up
Code for this example can be found on GitHub. After downloading the code, run
$npm install
followed by
$npm test
or this gulp command:
$gulp build
If you are using Visual Studio Code - you can build it using ⇧⌘B
(on Mac).
Testing
So I have this react component, named VeryFirstDiv:
In my previous post to test it I was creating fake DOM using JSDOM library and then rendering my testable component into this fake DOM (Read more about it here).
This time I’ll only use React TestUtils add-on and rather new feature of it - Shallow Rendering.
Shallow rendering is an experimental feature that lets you render a component “one level deep” and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.
In my test I create an instance of Shallow Renderer:
let renderer = ReactTestUtils.createRenderer();
Then, render my VeryFirstDiv component using this renderer
renderer.render(<VeryFirstDiv />);
and get the output:
myDiv = renderer.getRenderOutput();
At this point you can check anything you fancy. I’ll for example want to test whether it is of a type ‘div’ and does it have a class named “veryFirstDiv” Here’s my test:
For a comparison, I’ve created same test as in using DOM version:
Summary
Testing using Shallow Rendering is faster. You can even notice it on this small example: my test using fake DOM runs for ~50ms, while using Shallow Rendering test takes only 10ms. I believe the gain is even more significant on big projects. And as a pleasant side effect it doesn’t require additional libraries.
Happy Testing!