Search
  • Dan Dobos

Testing in React Part 2: Enzyme

In Testing in React Part 1: Jest, we learned how to use Jest to create tests in JavaScript. Jest is integrated into React with create-react-app but it can be also manually configured. In this tutorial, we will learn to use Jest in React with the help of a JavaScript Testing utility. Enzyme allows you to simulate the rendering of React components and ensures that their output and behavior are correct, making it easier to test your React application.


Enzyme needs to be installed along with an Adapter corresponding to the version of React you are using. The adaptor for react 17 from Enzyme is not out yet, but you can use the compatible unofficial @wojtekmaj variant.

yarn add --dev enzyme
yarn add --dev @wojtekmaj/enzyme-adapter-react-17

Create a setupTest.js file in the src folder, to configure Enzyme to use the adapter.

import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });

Update the test scripts inside package.json and you are ready to go!

"test": "jest",
"test:watch": "jest --watch",//
"test:coverage": "jest --coverage"
  • npm test will run all tests

  • npm run test:watch will run only tests that are related to files changed since the last commit

  • npm run test:coverage will run all tests and generate coverage report

Enzyme has three rendering types:

shallow() is used for unit testing, to test one isolated function or component, and can call lifecycles methods.


mount() is ideal to test functions working together, for use cases where you have components that may interact with DOM APIs or components that are wrapped in higher-order components. It does a full rendering that mounts the component in the DOM and is used for integration testing.


render() generates HTML from your React tree, and analyze the resulting HTML structure. It’s useful when you need to test HTML output.


Thank you for reading this post! I hope you find at least some of my recommendations useful! For improvements or other article suggestions, you can contact me on Linkedin. Soon to come...Testing in React Part 3: Snapshots


#react #testing #jest #enzyme


14 views0 comments

©2020 by CodeMasters and Skilltransfers