Ask Your Question
1

What is the method to utilize jest and enzyme to evaluate componentDidMount including document.getElementByClassName in React?

asked 2023-07-14 03:57:05 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-14 04:20:02 +0000

david gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-14 03:57:05 +0000

Seen: 13 times

Last updated: Jul 14 '23