1 | initial version |
To utilize Jest and Enzyme to evaluate componentDidMount including document.getElementByClassName in React, follow these steps:
npm install --save-dev jest enzyme enzyme-adapter-react-16
// setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import ComponentName from './ComponentName';
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');
});
});
componentDidMount() {
const element = document.getElementByClassName('example-class');
// do something with the element
}
npm run test