How to setup Jest and Enzyme in existing React application?

Writing test cases for an application makes the application solid. It is proven that the application will have fewer flaws if test cases are properly written. Writing test cases became a norm for all robust applications.

As a developer, if we write a feature without test cases then it feels incomplete. Some developers also prefer to write test cases first and then write actual code. This approach is known as test-driven development (TDD).

In React application, it is really simple to write test cases from day one. If we create a ReactJS application using create-react-app boilerplate, then the test runner Jest is automatically included. No Jest setup is required in that case.

We only need to install Enzyme and add an adapter to make it work with Jest.

How to install Enzyme?

To install Enzyme in a ReactJS application we need to add the dependency to the package.json file. We can use both npm or yarn package manager to add it.

By using NPM

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

By using YARN

$ yarn add enzyme --save-dev
$ yarn add enzyme-adapter-react-16 --save-dev

Configuration for Enzyme

We need to configure Jest and Enzyme to work together with React. To make them work together we need to create a new file called setupTests.js in the src/ directory. Put the following content inside that directory.

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

Now, we are pretty much ready to write our first test case based on Jest and Enzyme.

The component: App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

The test case: App.test.js

import React from 'react';
import { shallow } from 'enzyme';
import App from './App';



describe('Application home page test cases', () => {
  test('Anchor needs to have proper text', () => {
    const element = shallow(<App />);
    expect(element.find('a').text()).toBe("Learn React");
  });
});

How to run the test?

$ yarn test 
or
$ npm test

The output:

 PASS  src/App.test.js
  Application home page test cases
    ✓ Anchor needs to have proper text (11ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.168s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.
Reference: