Configuring JEST and Enzyme with React Apps

You can configure JEST with React Apps in few simple steps. Let’s follow these steps and get JEST ready into our React Apps.

Step 1:

You can setup your React App the way you want to with all your files residing under the src folder as in this project: react-redux-boilerplate.
All the dependencies for this app is present under in package.json.

Step 2: 

Setup your .babelrc file so that you can work on JEST with ES6 as follows

{
  "presets": ["react", "env", "stage-1"]
}

Step 3:

Configure enzyme so that the enzyme functions are available globally.

setupTests.js

Note:- Please make sure that you don’t name your file as jest.config.js, because that is the default file provided by JEST for its configuration, if done so, JEST won’t understand the difference in its own configuration and enzyme. Refer: problem-solution-stackoverflow

import { shallow, render, mount, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
// React 16 Enzyme adapter
configure({ adapter: new Adapter() });
// Make Enzyme functions available in all test files without importing
global.shallow = shallow;
global.render = render;
global.mount = mount;

Step 4:

Configure JEST in your package.json as follows:

 "scripts": {
    "test": "jest"
  },
  "jest": {
//as we are accessing our application with a http://localhost prefix, we need to update our jest configuration
    "verbose": true,
    "testURL": "http://localhost/",
    "transform": {
      "^.+\\.js$": "babel-jest"
    },
    "setupFiles": [
      "./setupTests.js"
    ],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  },

Step 5: 

Now you can start writing your tests inside the test or __test__ folder under src directory.
In order to execute your test cases simply run the command npm run test in your terminal. After executing this command, you will the following in your terminal:

Screen Shot 2018-08-17 at 1.07.48 AM

In order to know more about JEST and writing more unit tests, you can go to the official JEST documentation.

So now that we have a JEST React Redux boilerplate ready, we are good to go and can start implementing TDD. Hope this helps !

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s