Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To utilize Jest and Enzyme to evaluate componentDidMount including document.getElementByClassName in React, follow these steps:

  1. Install Jest and Enzyme:
npm install --save-dev jest enzyme enzyme-adapter-react-16
  1. Create a setup file for Enzyme:
// setupTests.js

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });
  1. Import Enzyme and React in your test file:
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
  1. Import the component you want to test:
import ComponentName from './ComponentName';
  1. Write the test:
describe('ComponentName', () => {
  it('should call componentDidMount and update state', () => {
    jest.spyOn(ComponentName.prototype, 'componentDidMount');
    const wrapper = shallow(<ComponentName />);
    expect(ComponentName.prototype.componentDidMount).toHaveBeenCalledTimes(1);
    expect(wrapper.state('exampleState')).toEqual('exampleValue');
  });

  it('should call the correct function on button click', () => {
    const wrapper = shallow(<ComponentName />);
    const button = wrapper.find('.example-button');
    button.simulate('click');
    expect(wrapper.state('exampleState')).toEqual('newValue');
  });
});
  1. In your component, use document.getElementByClassName to select elements:
componentDidMount() {
  const element = document.getElementByClassName('example-class');
  // do something with the element
}
  1. Run the test command:
npm run test