Part 2 Testing React Applications – Enzyme Shallow and Full rendering

Hi, we need to open our project “todos” in the code editor and go to todo/src/components/ and create the file called todo.test.js we are going to create the unit test code here. 

In order to create our test we need to import React, Todo component. 

The next step is install Enzyme that is a utility provided by Airbnb here the link.

Enzyme is “Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components’ output. You can also manipulate, traverse, and in some ways simulate runtime given the output.”

The API reference is a really good resource to find all the code definition and examples of how to use Enzyme.

Let me explain you the 2 rendering ways of Enzyme

Shallow rendering 

For use the shallow rendering we need to import shallow from enzyme.

Shallow rendering is good if we have a very basic react component that doesn’t have a child components and also if you just want to write unit test for your react component in isolation.

For example this todo component only have html and onClick method and does not have other child components:

Full rendering

For use the full rendering we need to import mount from enzyme.

This is very usable in react, for example if we want to test componentDidMount and componentDidUpdate you have to use mount and also if your component have child component and you want to assert, verify or inspect certain things within the child component you need to user full rendering. 

For example, this App component have 3 child components, in this case you need to use mount of enzyme will be the way for implement the test in this component: 

Ok for now we complete the part 2 of testing react applications, I will publish the part 3 of this course. 

Read Part 1:

Part 1 Testing React Applications – Environment

Criss.