What is jest-enzyme?
The jest-enzyme package provides a set of custom matchers for using Enzyme with Jest, making it easier to write and read tests for React components.
What are jest-enzyme's main functionalities?
toBeChecked
This matcher checks if a checkbox input is checked.
expect(wrapper.find('input[type="checkbox"]').first()).toBeChecked();
toHaveClassName
This matcher checks if a component has a specific class name.
expect(wrapper.find('.my-class')).toHaveClassName('my-class');
toHaveStyle
This matcher checks if a component has a specific inline style.
expect(wrapper.find('div')).toHaveStyle('display', 'none');
toContainReact
This matcher checks if a component contains a specific React element.
expect(wrapper).toContainReact(<MyComponent />);
toHaveText
This matcher checks if a component contains specific text.
expect(wrapper.find('p')).toHaveText('Hello World');
Other packages similar to jest-enzyme
jest-dom
jest-dom provides a set of custom matchers to test the state of the DOM. It is similar to jest-enzyme but is more focused on testing DOM nodes rather than React components specifically.
enzyme
Enzyme itself is a testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output. jest-enzyme is built on top of Enzyme to provide Jest matchers.
react-testing-library
react-testing-library is a lightweight solution for testing React components. It encourages testing components in a way that is similar to how users interact with them. It can be used with Jest and provides a different approach compared to Enzyme.
jest-enzyme
Installation
We suggest using yarn for installations.
yarn add jest-enzyme --dev
But npm works too!
$ npm install jest-enzyme --save-dev
Setup
The simplest setup is to use jest's setupTestFrameworkScriptFile
config.
On older versions of Jest,
you'll also need to tell jest to unmock react
, enzyme
, and jest-enzyme
.
Make sure your package.json
includes the following:
"jest": {
"setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js",
"unmockedModulePathPatterns": [
"react",
"enzyme",
"jest-enzyme"
]
},
If you are using Create React App, instead of adding to your package.json
as above, you will need to add a src/setupTests.js
file to your app, to import jest-enzyme:
import 'jest-enzyme';
This is documented on Create React App at the bottom of the Testing Components section. There is also more information about Initializing Test Environment.
Also, instead of installing the latest version you should stick with versions below 3, because Create React App currently uses a version of jest which will cause this issue:
yarn add jest-enzyme@2.1.2 --dev