6. Testing react components using Jest and Enzyme

Agata Krzywda
2 min readMar 22, 2017

--

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
  1. 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 variable items
  • Now we are writing our first test case for the component using renderer.create().toJSON(); method and adding last line expect(tree).toMatchSnapshot(); for create a snapshot in a separate folder __snapshots__ where we have a file App.test.js.snap which stores our component output.
  • To run test npm test and to update snapshots npm 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 /> using shallow() function and does it “one level deep”
  • Then inside setState() we pass our items
  • Then we find form element usingfind() method from enzyme. We will simulate a submit event on this element by passing a dummy event.
  • Last thing toMatchSnapshots() and toBeCalled() methods. Which check if components json which we got from toJson() function matches the existing snapshot, as well as if preventDefault 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 /> using shallow() function and does it “one level deep”
  • Then inside find() method we pass the element on which we want simulate change event, which we define and pass to our simulate() function, we also need to pass an object with a key target which contains another object storing the value “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:

  1. Jest facebook documentation
  2. Testing React Applications by Max Stoiber
  3. Testing React components with Jest and Enzyme by Artem Sapegin

This how our components and test files should look like:

Code at github

Enjoy :)

--

--