6. Testing react components using Jest and Enzyme
This is the sixth part of my React tutorials. See the Intro to react.js here
In this tutorial we will be testing our todo list with Jest and Enzyme.
First we need install few libraries:
npm install jest babel-jest enzyme enzyme-to-json react-addons-test-utils --save-dev
- Now let’s open
App.test.js
file and add this:
- First we import all libraries which we need for testing
- Then we create a
describe
block for our component and variableitems
- Now we are writing our first test case for the component using
renderer.create().toJSON();
method and adding last lineexpect(tree).toMatchSnapshot();
for create a snapshot in a separate folder__snapshots__
where we have a fileApp.test.js.snap
which stores our component output. - To run test
npm test
and to update snapshotsnpm test -- -u
App.test.js.snap
file should look like this now:
2. Test onSubmit function by creating second test case:
- First we create a variable
component
which renders our <App /> usingshallow()
function and does it “one level deep” - Then inside
setState()
we pass ouritems
- Then we find
form
element usingfind()
method from enzyme. We will simulate asubmit
event on this element by passing a dummy event. - Last thing
toMatchSnapshots()
andtoBeCalled()
methods. Which check if components json which we got from toJson() function matches the existing snapshot, as well as ifpreventDefault
object has been called. Note:preventDefault
normally is a method which prevents default functionality of the event and lets you do with the event something else instead.
3. Test onChange function by creating third test case:
- First we create a variable
component
which renders our <App /> usingshallow()
function and does it “one level deep” - Then inside
find()
method we pass the element on which we want simulatechange
event, which we define and pass to oursimulate()
function, we also need to pass an object with a keytarget
which contains another object storing thevalue
“Change function”
Now our App.test.js.snap
snapshots file should look like that:
Last thing to test isList.js
which is an easy part.
Here we will be checking if our component received props
from <App /> by passing items={items}
to the <List /> component and checking snapshot to match with toMatchSnapshot()
inList.test.js.snap
file.
Jest and Enzyme are very good for testing components in React because their are simple, easy to use, convenient utilities to work with shallow rendering, snapshot testing and many more reasons.
The best resources which I found about jest and enzyme are:
- Jest facebook documentation
- Testing React Applications by Max Stoiber
- Testing React components with Jest and Enzyme by Artem Sapegin
This how our components and test files should look like:
Enjoy :)