Testing in React (Jest & Enzyme)

Arvind Dhakar
2 min readJun 12, 2021

--

Photo by Christina @ wocintechchat.com on Unsplash

Jest acts as a test runner, assertion library, and mocking library.

Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components’ output (basically used for dom impersionation for testing react component).

  1. Three things (Jest)
  • Test suites (describe block)
  • Test cases (test or it block)
  • Test Assertion (expect block)

2. Rendering methods (enzyme)

  • shallow(render only parent)
  • mount (deep rendering(render also children)
  • render(static rendering(HTML))

3. Test assertion (enzymes || jest)

  • expect().toBeTruthy()
  • expect(.find()).toBeLength()

a. Test assertion for functions

  • toHaveBeenCalledTimes() how many times a function called
  • toHaveBeenCalledWith() to verify arguments

4. Simulating event

wrapper.find('input').at(1).simulate('change', { target: { name: 'height', value: 70 } });
expect(testState.height).toEqual(70);
  • simulating in Enzyme same as firing event in RTL
  • .simulate

5. SnapshotTesting

import React from 'react';
import toJSON from 'enzyme-to-json';
import { shallow } from 'enzyme';
import { MyViewComponent } from '../';
describe('<MyViewComponent />', () => { it('Should render correctly', () => { const props = {
prop1: expect.any(String)
};
const component = shallow(<MyViewComponent {...props} />); expect(toJSON(component)).toMatchSnapshot();
});
});

6. Facing testing issue related to hooks used in your testing component

Used jest.mock to mock functionality of hook used

jest.mock(‘react-router-dom’, () => {
const actual = jest.requireActual(‘react-router-dom’);
return {
…actual,
useRouteMatch: () => ({
url: ‘dashboards/all’
})
};});

--

--

Arvind Dhakar
Arvind Dhakar

No responses yet