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",
"jasmine-enzyme"
]
},