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.
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.
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.
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.
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:
Writing extensive tests becomes easier over time, just as testing becomes second nature over time.
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:
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.
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.
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.
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.
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 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.
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 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.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to implement one-way and two-way data binding in Vue.js, using v-model and advanced techniques like defineModel for better apps.
Compare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
2 Replies to "Jest and Enzyme: Unit testing in React in 2021"
Why not React Testing Library?
Does it works well with React 17??
Specifically this issue: https://github.com/enzymejs/enzyme/issues/2429