Brian Emil Hartz

let me = enjoy ( pondering ( javascript ( reactjs ) ) )

Simply test react components


With react v0.13 they introduced 'shallow rendering', all basic html inside a component is rendered and no sub components are rendered. We now have the power to run unit tests in node without the need for a 'DOM'.

Shallow Rendering takes a component and renders it 'one level deep' and will not render sub components. This allows unit tests to keep focus on their specific component.

This post walks through writing simple tests for an example component <List/> which contains <Item/> components.

These testing examples use the TAP library tape and airbnb's newly open sourced react component testing utilities enzyme for react components.

Example <List/> component:

When writing unit tests for <List/> the tests should focus on the output of <List/> and not what <Item> does with the item data.

Example tests for <List/>:

These unit tests focus on <List/> and make assertions as to what it will render, and are not concerned with what <Item/> will render. <Item/> has its own specific unit tests.

Example test for <Item/>:

Sum

This post is intended to be an easily digestible and simple intro to testing react components. Unit tests for react components can be quick and simple while adding confidence to your code base.

Please check out the repo simple-react-enzyme-examples if you'd like to run/check out these examples!