React Test Renderer Simulating Clicks on Elements

前端 未结 2 936
太阳男子
太阳男子 2021-01-07 22:32

I\'m testing a React component using Jest v16.0.1, react-test-renderer v15.4.0 and react-addons-test-utils v15.4.0.

The component has rendered a button:



        
2条回答
  •  情话喂你
    2021-01-07 22:38

    Maybe it's too late but find is an API from enzyme. The answer on the question you referred to assumed enzyme is used as mentioned on the comment.

    Something like this should work.

    MyComponent.jsx

    import React from 'react';
    
    class MyComponent extends React.Component {
      constructor() {
        super();
        this.state = {
          cancelButtonDisabled: false,
        };
      }
      handleCancel() {
        this.props.cancelAction();
      }
      render() {
        return (
          
        );
      }
    }
    
    export default MyComponent;
    

    MyComponent.test.jsx

    import React from 'react';
    import {mount} from 'enzyme';
    import MyComponent from './MyComponent';
    
    describe('Test MyComponent', () => {
      it('should be able to click the button', () => {
        const mockFunction = jest.fn();
        const element = mount();
        element.find('button').simulate('click');
        expect(mockFunction).toHaveBeenCalled();
      });
    });
    

    without enzyme, it would look like this.

    MyComponentWithoutEnzyme.test.jsx

    import React from 'react';
    import ReactDOM from 'react-dom';
    import ReactTestUtils from 'react-addons-test-utils';
    import MyComponent from './MyComponent';
    
    describe('Test MyComponent', () => {
      it('should be able to click the button', () => {
        const mockFunction = jest.fn();
        const element = ReactTestUtils.renderIntoDocument(
          ,
        );
        const button = ReactDOM.findDOMNode(element);
        ReactTestUtils.Simulate.click(button);
        expect(mockFunction).toHaveBeenCalled();
      });
    });
    

提交回复
热议问题