Andrew Evans Climbing mountains and tackling technology challenges for over eight years in the mile high state.

Jest and Enzyme: Unit testing in React in 2021

4 min read 1234

jest enzyme react unit testing

Unit testing in React in 2021 has come a long way since the early days of the framework. Tools such as Jest and Enzyme reduce coding errors entering production by as much as 40 to 80 percent. There is no longer a need to roll your own solution when deploying these extensive frameworks.

In this article, we’ll look at how to build unit tests for React using Jest and Enzyme and learn how to reliably test component trees and functions.

Prerequisites

This tutorial requires a basic knowledge of React. We rely on Node.js to serve content.

You need to install several libraries to work with Jest and Enzyme. Include the following section in your Node.js package.json file or install the packages using npm:

"devDependencies": {

"@babel/preset-env": "7.12.7",

"@babel/preset-react": "^7.12.7",

"babel-jest": "^26.6.3",

"jest": "^26.6.3",

"react-test-renderer": "^17.0.1"

}

While React is a frontend framework, we’ll focus on running tests using Node.js. You will use the npm command to run tests.

A sample React program

Before diving into unit testing, we need to create a simple program. We create a function that returns the result of a simple computation and another that renders content.

Add the following to your index.js or custom JavaScript file:

function getComputation(a, b){
return a + b;

}
function sayHello(){
return <div><p>Hello World!</p></div>;

}

Start your web server and open the index page for your application. Ensure that the page displays the “Hello World!” text.

What are unit tests in React?

Assume the sayHello function stopped returning the right content or failed entirely. You would want to know that the method stopped working before moving to production.

Unit tests ensure that your code works as expected early in production. Developers incorporate them when writing functions to make sure that each works as it should. Tests are extremely effective when coupled with strong logging.

We made a custom demo for .
No really. Click here to check it out.

Writing good unit tests

Testing needs to be thorough, which takes time and effort. Still, writing expansive suites creates peace of mind while ensuring that your application does not fail unexpectedly and drive away users in the process.

Good unit tests:

  • Test individual functions
  • Write tests for expected behavior and functionality
  • Rely on a common language for different assets and behaviors
  • Provide insight into issues through logs and other information

Writing extensive tests becomes easier over time, just as testing becomes second nature over time.

The impact of coding best practices on testing

There are a few best practices to follow to improve both the capability of your tests and your code quality. Coding standards and best practices go hand in hand with keeping your applications functioning smoothly.

To make it easier to run tests and work with applications:

  • Split repeated code into individual and testable functions
  • Avoid combining functionality
  • Do not bury critical code

Cluttered code that is difficult to read through, wrapping many pieces of functionality in a single function, makes testing more difficult. Bad practice also makes future development more difficult.

Unit tests in Jest and Enzyme

Jest and Enzyme allow you to write strong unit tests without building a framework from scratch. These tools wrap tests in a more natural manner than writing individual functions and also give you access to reporting and assertions.

Create index.test.js in a location under your src folder. Write a test for the getComputation function in this file:

const idx = require('./index.js')
describe("testComputation", () =>{
it('adds 1 + 5', () =>{


    expect(idx.getComputation(1, 5)).toBe(6);


});

});

We ensure that the program returns the right result. You still need to tell the test runner about your test.

Write the following configuration in a new file titled testconfig.json:

{

"verbose": true,

"testURL": "http://localhost/",

"testMatch": ["**index.test.js?(x)"]

}

Change the testMatch array to match the path to test.index.js. You can tell Jest to read tests from any file using a regular expression.

Finally, add the following to package.json to tell Node how to run your unit tests:

"scripts": {

"test": "jest",

}

Run the test from the command line:

jest testComputation –config=./testconfig.json

Jest will run the testComputation test in the test.index.js file. Details of each test appear in your console.

DOM testing

React offers a DOM renderer. Enzyme builds on this to let you test individual components. You can verify individual components.

The sayHello function returns a div. You can create the following test to ensure that the page renders correctly:

import {shallow} from 'enzyme';
describe("testRender", () =>{
it("should render hello world", () => {


    const html = idx.sayHello();


    const wrapper = shallow(html).toJSON();


    expect(wrapper.text()).toContain("Hello World!");


});

});

Unless you change the tree, the division will look the same. This ensures that the resulting content remains consistent. Detecting unwanted changes helps improve the user experience.

What does Enzyme do?

In the test case above, Enzyme provides a mechanism for mounting and traversing React.js component trees. The framework lets you easily assert, manipulate, and traverse components.

Unlike in the past where you may not have had access to the renderer, Jest can render the content while Enzyme lets you test assumptions about the content. This can save you from writing potentially buggy use cases in which you need to match against strings as shown above.

Logging with Enzyme

Enzyme can also serve as the window into your unit tests. There is nothing more frustrating than having a test fail without reason, especially if you’re using a dependency that does not offer decent logs.

You can wrap objects and print them to the console:

const html = idx.sayHello();

const wrapper = shallow(html).toJSON();

console.log(wrapper.debug());

Log this information to a central location if you’re running your tests within a continuous integration framework. Your chosen tool may already aggregate information from the console, but you can always store these logs in Elasticsearch using Logstash or another searchable log storage platform.

Unit tests in continuous integration

Unit tests are part of a broader strategy to ensure application health. They are the first step to reducing the number of bugs in your systems.

Using them in continuous integration tools keeps your applications from breaking after an update. Continuous integration automates builds, which can be a problem if something breaks unexpectedly.

Tools such as Circle CI and Gitlab CI let you run tests in a Docker container as part of the build process. The entire build fails if your tests do. Make sure to log on to an Application Performance Management or another logging tool to keep track of issues in your builds.

Code coverage

As your application grows, making sure that you test thoroughly becomes more difficult. Code coverage, the amount of source code run through your tests, is a useful statistic to track. Use a code coverage tool to find untested parts of your project.

Jest allows you to track this statistic when running tests. Simply use the –coverage option from the console and get ready to work toward 100% on your Jest GitHub code coverage badge. The resulting report shows statements, branches, functions, and lines reached.

Unit testing in React in 2021

Unit testing is an important part of development. It reduces errors, increases productivity, and eliminates time otherwise spent debugging code.

Jest is a powerful platform that gives you the ability to perform thorough unit testing in React in 2021. Deploy your tests to your chosen continuous integration tool and make logs accessible to keep your applications healthy.

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Andrew Evans Climbing mountains and tackling technology challenges for over eight years in the mile high state.

One Reply to “Jest and Enzyme: Unit testing in React in 2021”

Leave a Reply