Flat Preloader Icon

Using Jest and Enzyme

To get started with testing using Jest and Enzyme in a React project, follow these steps

Setting Up Jest and Enzyme

Step 1: Install Dependencies

First, ensure you have Jest, Enzyme, and the necessary adapters installed. If you’re using React 16, the command would be:

npm install --save-dev jest enzyme
enzyme-adapter-react-16

For React 17, replace enzyme-adapter-react-16 with enzyme-adapter-react-17

Step 2: Configure Enzyme Adapter

Create a file named setupTests.js in the root of your project (or in the src directory, depending on your project setup). Add the following configuration

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

For React 17, use:

import { configure } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

configure({ adapter: new Adapter() });

Ensure that Jest is aware of this setup file. In your package.json, add the following under the Jest configuration

"jest": {
  "setupFilesAfterEnv": ["<rootDir>/setupTests.js"]
}

Writing Tests

Example Component

Let’s say you have a simple Button component:

// Button.js
import React from 'react';

const Button = ({ onClick, children }) => (
  <button onClick={onClick}>
    {children}
  </button>
);

export default Button;

Writing a Test for the Component

Create a test file for the Button component, typically named Button.test.js:

// Button.test.js
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';

describe('Button Component', () => {
  it('should render correctly with given props', () => {
    const wrapper = shallow(<Button>Click Me</Button>);
    expect(wrapper.text()).toEqual('Click Me');
  });

  it('should call onClick when button is clicked', () =>
  {
    const onClickMock = jest.fn();
    const wrapper = shallow(<Button onClick=
    {onClickMock}>Click Me</Button>);
    wrapper.find('button').simulate('click');
    expect(onClickMock).toHaveBeenCalledTimes(1);
  });
});

Running Tests

Run your tests using the following command:
npm test

Example Project Structure

Your project structure should look something like this

my-app/
├── src/
│   ├── components/
│   │   ├── Button.js
│   │   ├── Button.test.js
│   ├── setupTests.js
├── package.json
├── node_modules/
├── ...