Jest React Testing
UI Development

Basic setup for Unit Testing React Components using Jest

React is a JavaScript library for building user interfaces. React is used to build single page applications. React allows us to create reusable UI components.

Unit testing is the first level of software testing where each components of software are tested.

Why Unit Testing?

  • It  helps in finding bugs in development phase.
  • It helps in writing code in the modular way, covering all the edge cases.
  • It helps the fellow peers to understand the what code should work as.
  • Good Unit Testing will be served as documentation as well.

In this blog, we’ll discuss on the tools required and setup for testing the react components.

We use 2 tools for testing React components:

  • Jest – JavaScript Testing Framework
  • Enzyme – React specific testing library

Lets’s Start!

At first, create react app by the command

npx-create-react-app my-app

If setup is without create-react-app then, run the following command,

npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer

In package.json file, change the scripts test as follows

"scripts": {
    "test": "jest"

To find the coverage of the tests, we need to add this in the scripts in package.json that gives the coverage report in the coverage folder as NYC is integrated in Jest. We can check the coverage from the corresponding report from coverage directory.

"scripts": {
    "test": "jest --coverage"

Using create-react-app, just few jest configurations can be altered in package.json

There will be problems with Jest taking up an internal library, it will show ‘unexpected token’ errors when some had imports from this library.

To solve that, add the following in the package.json

"jest": {
    "transform": {
      "\\.js$": "/node_modules/babel-jest"

Add the following in the babel.config.js

// babel.config.js
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],

Test files format

The test files can be written either in the __tests__ folder with the component name or with the extension .test.js

For example:

In __tests__ folder


or with test.js format


Types of Testing

Snapshot Testing

Snapshot testing is using for the case where the UI doesn’t change unexpectedly.

Instead of taking complete application building for rendering UI graphically, it generates serialized values for React tree.

Consider a Link component

import React, { Component } from 'react';

export class Link extends Component {
  constructor(props) {

    this.mouseOn = this.mouseOn.bind(this);
    this.mouseOff = this.mouseOff.bind(this);

    this.state = {
      class: 'default',

  mouseOn() {
    this.setState({class: 'hover'});

  mouseOff() {
    this.setState({class: 'default'});

  render() {
    return (
export default Link;


The Link component updates the states on the mouse actions on the corresponding <a> tag. On mouse enter the state class updates to ‘hover’ and on mouse leave the state updates to ‘default’.

Let’s write the unit test case for the Link component.

Test file for the Link component.

import React from 'react';
import Link from './Link';
import renderer from 'react-test-renderer';
test('Link class change takes place when hovering', () => {
  const component = renderer.create(
    <Link page="">TA Digital</Link>,
  let tree = component.toJSON();
  // manually trigger the callback
  // re-rendering
  tree = component.toJSON();
  // manually trigger the callback
  // re-rendering
  tree = component.toJSON();

The renderer function from ‘react-test-renderer’ library is to create a serializable value for your React tree.

renderer.create() creates the snapshot of the component provided.

expect() takes the snapshots of the current component and .toMatchSnapshot() compares to the previous snapshots.

When run npm run test

npm run test

will produce the output file with .snap extension (snapshot) in __snapshots__ directory.


// Jest Snapshot v1,

exports[`Link changes the class when hovered 1`] = `

  TA Digital


exports[`Link changes the class when hovered 2`] = `

  TA Digital


exports[`Link changes the class when hovered 3`] = `

  TA Digital


From later running the tests, the rendered output will compare to previously created snapshot. The snapshot must be committed along code changes.

When a test fails, then we need to rectify the change is either intended or unintended. If change is expected then we have to invoke Jest with option -u to change the existing snapshot.

DOM Testing

It is suitable for assert, and manipulate rendered components.

Here in the DOM Testing we use Enzyme package.

npm i --save-dev enzyme enzyme-adapter-react-16

Enzyme is a JavaScript Testing utility for React to test React Components. We can traverse, manipulate, and in some ways simulate runtime given the output.

Consider CheckboxWithLabel component

import React, { Component } from 'react';

export class CheckboxWithLabel extends Component {
  constructor(props) {
    this.state = {isChecked: false};
    this.onChange = this.onChange.bind(this);

  onChange() {
    this.setState({isChecked: !this.state.isChecked});

  render() {
    return (
        {this.state.isChecked ? this.props.labelOn : this.props.labelOff}

export default CheckboxWithLabel;

The component works like, the state will be updated on the user input of checkbox. And based on the checkbox input value, the corresponding label will be displayed.

Let’s test the component:

Here, there are two types of component rendering can happen.

  • Shallow: This type of rendering only renders the component and doesn’t render the child component.
  • Mount: Mount will render the present components with children components.

It is advised to use Shallow rendering for testing individual components.

Here is the test file for CheckboxWithLabel component:

import React from 'react';
import Enzyme, {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16'
import CheckboxWithLabel from '../CheckboxWithLabel';
Enzyme.configure({ adapter: new Adapter() })
test('Label changes when on checked', () => {
  // Renders a checkbox component with label
  const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);

shallow() from enzyme will render the given component itself (i.e., CheckboxWithLabel). By initial rendering, the component should have label text as ‘Off’.

find() is used to check for the tags based on the tag names, classnames, ids etc…

simulate() is to interact with the component to give the input to the component. As the input changes, the corresponding label text should also be changed to ‘On’.

expect() will retrieve the resultant text and toEqual() will compare the the obtained data (received) to the given data (expected).


Testing React components is very valuable. It will increase the stability and quality of the code.


About The Author