React is a JavaScript library for building user interfaces and Jest is a testing framework to test the React components. In this article, we will go through the installation of Jest as well as get started with the testing of React component. We will also overcome some of the common issues faced during the installation of Jest.
Table of Contents
Step 1: Visit the official JEST documentation page
It is always the best idea to initially head over to the official documentation. You can find that page right here.
Step 2: Create the test folder
Create a folder named “__test__
“. This folder will contain all the test files.
Step 3: Use “npm install” to install the packages
Use the terminal to run the following commands.
Install jest:
npm install --save-dev jest
Step 4: Update package.json
Add the following code to your package.json file
“Scripts”: { .... “test” : “jest” .... }
If your package.json already consists a “test” object with some different value, replace it with the code given above. Once done, your scripts object might look like this.
"scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "jest", "eject": "react-scripts eject" }
Note: As pointed out by Dan Abramov, if you are using the create-react-app boilerplate, you would not have to add the react-script explicitly. Create React App includes and uses Jest as its test runner.
Step 5: Create files for testing
I will use the same example from the documentation, to check if we are up and running. I am creating two files:
sum.js
– It will have a simple function to add two number, that we want to test.
function sum(a, b) { return a + b; } module.exports = sum;
sum-test.js
– This will contain my actual test script. This file will be inside the __test__ folder
const sum = require('./sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
This code passes two parameters (1, 2) to the sum(a, b) function and expects the result to 3, which is obviously the sum of 1 and 2.
Step 6: Run “npm test”
In the command line, all we do now is run:
npm test
That’s it! Our code run and it passes the test. We have been able to successfully test a JavaScript function using JEST.
We can generalize the syntax as:
test("Output to display", () => { expect(functionName(param1, param2)).toBe(output); });
Step 7: Testing on React components
Before we begin, install the following dependencies:
npm install --save-dev babel-jest babel-polyfill npm install --save-dev jest babel-jest babel-preset-es2015 babel-preset-react react-test-renderer npm i --save-dev enzyme
We will be also using Enzyme, which is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components’ output.
I am using the example of DOM testing which is given on the official documentation page of JEST. As shown in the documentation I will be creating two files: CheckBoxWithLabel.js
and CheckBoxWithLabel-test.js
in __test__ folder.
In this example, we are implementing a checkbox which swaps between two labels “On” and “Off”
CheckBoxWithLabel.js:
import React from 'react'; export default class CheckboxWithLabel extends React.Component { constructor(props) { super(props); this.state = {isChecked: false}; this.onChange = this.onChange.bind(this); } onChange() { this.setState({isChecked: !this.state.isChecked}); } render() { return ( <label> <input type="checkbox" checked={this.state.isChecked} onChange={this.onChange} /> {this.state.isChecked ? this.props.labelOn : this.props.labelOff} </label> ); } }
CheckBoxWithLabel-test.js
import React from 'react'; import {shallow} from 'enzyme'; import CheckboxWithLabel from '../CheckboxWithLabel'; test('CheckboxWithLabel changes the text after click', () => { const checkbox = shallow( <CheckboxWithLabel labelOn="On" labelOff="Off" /> ); expect(checkbox.text()).toEqual('Off'); checkbox.find('input').simulate('change'); expect(checkbox.text()).toEqual('On'); });
But when we try to run this test by typing npm test
, we might encounter such errors:
FAIL src/__tests__/CheckboxWithLabel-test.js ● Test suite failed to run /home/adityae/my-app/src/__tests__/CheckboxWithLabel-test.js: Unexpected token (11:8) 9 | // Render a checkbox with label in the document 10 | const checkbox = shallow( > 11 | <CheckboxWithLabel labelOn="On" labelOff="Off" /> | ^ 12 | ); 13 | 14 | expect(checkbox.text()).toEqual('Off'); FAIL src/App.test.js ● Test suite failed to run /home/adityae/my-app/src/App.test.js: Unexpected token (7:18) 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); > 7 | ReactDOM.render(<App />, div); | ^ 8 | }); 9 | PASS src/__tests__/sum-test.js Test Suites: 2 failed, 1 passed, 3 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 25.688s Ran all test suites. npm ERR! Test failed. See above for more details.
And this maybe because your code is not transpiled. Solution to this problem is adding a .babelrc
file.
Next, create a .babelrc
file with the following content:
{ "presets": ["es2015", "react"] }
This passed the second test which meant the code transpiled but it still failed the test for the component with the error:
Cannot find module 'react-dom/lib/ReactTestUtils'
The issue is- react-addons-test-utils 15.4.0 has a peer dependency on react-dom and uses it, 15.3.0 had a peer dependency on react.
Source: https://github.com/facebook/react/issues/8314
Use the following command to overcome this problem:
npm install react-dom --save[-dev]
Enzyme is currently compatible with React 15.x, React 0.14.x and React 0.13.x. In order to achieve this compatibility, some dependencies cannot be explicitly listed in our package.json.
If you are using React 0.14 or React 15.x, in addition to enzyme, you will have to ensure that you also have the following npm modules installed if they were not already:
npm i --save-dev react-addons-test-utils npm i --save-dev react-dom
Source: https://github.com/airbnb/enzyme
Now you are ready to test your app, Again enter the npm test
command in your terminal.
Once completed your terminal will output something like this:
PASS __tests__/CheckboxWithLabel-test.js (0.869s) 1 test passed (1 total in 1 test suite, run time 1.973s) s
This is it to get started with testing React components using Jest. I would be happy to know more from your side if you faced any other issue while installing Jest and the measures you took to overcome it!