Unit testing a React Component with Jest + Enzyme.

uchechukwu Inyama
3 min readJul 7, 2020

This article will help you configure Enzyme to test a react component scaffolded with create-react-app. 😃

Jest is a testing framework developed at Facebook, and Enzyme, developed at Airbnb, is a library for manipulating your react component while testing.

Since we scaffolded the project with create-react-app, a lot of configuration has been done for us under the hood, especially for Jest. However, to use Enzyme in this test, we have to do some work, setting up Enzyme.

To setup Enzyme, run the following command on your terminal:

If you are using yarn: yarn add enzyme enzyme-adapter-react-16

If you are using npm: npm install — save enzyme enzyme-adapter-react-16

Then, add the following code snippet to src/setUpTests.js

Let’s take a detour; there are some terms I would like us to be familiar with, while writing your test.

describe, it, expect, beforeEach, afterEach and matchers.

Please, go here to understand how they work. Caveat, while reading, you will see Jasmine, but don’t worry about it, the instructions apply to Jest; in fact, Jest extends from Jasmine. 😉

Since we are writing unit tests, we would be testing components in isolation. To test each component in isolation from their child component, we would use Enzyme’s shallow() method which returns a shallowWrapper object. To get an intuitive understanding of shallow rendering, watch this video

Having a good mental model of anything you want to do is important. So, while testing a react component have these in mind:

  • First, render the component you’re testing.
  • Then, go on to make your assertions.

The component we will be testing is, ItemList component:

In the above lines of code, we have used beforeEach to render the component we want to test, then made our assertions inside “it” function. The wrapper object has a method find, I used the matcher toBe, for the assertion.

In the lines of code above, we tested an API call, I won’t go into details, however, it follows the same pattern that a component has to be rendered first before an assertion is carried out. If you are interested in learning more about testing components with API call check out this article, but understanding how to mock in Jest is important.

In conclusion, writing tests is challenging most times, however, having a good background makes a lot of difference. This article, serves as a simple guide, to help you hit the ground running if you are writing tests with Jest+Enzyme, for react components scaffolded with create-react-app.

--

--