Как вызвать цель события внутри функции с помощью enzyme — React

#reactjs #enzyme

#reactjs #enzyme

Вопрос:

   componentWillUnmount() {
        document.removeEventListener('click', this.handleClickOutside);
    }

    /**
   * Set the wrapper ref
   */
    setWrapperRef(node) {
        this.wrapperRef = node;
    }

    handleClickOutside(event) {
        /* istanbul ignore next */
        if (this.wrapperRef amp;amp; !this.wrapperRef.contains(event.target)) {
            this.props.clickHandler();
        }
    }
  

Как мне вызвать handleClickOutside функцию. Как я должен имитировать clickOutside здесь? Пожалуйста, помогите

  it('lets click outside and close dropdown', () => {
        const handleClickOutside = sinon.spy();
        expect(handleClickOutside.called).to.be.true;
        wrapper.unmount();
    });
  

Ответ №1:

Предполагая, что это HOC or render prop , который отображает другие компоненты как children ( this.props.children ) — также ниже приведен тест Jest и Enzyme , поэтому он может немного отличаться от того, что вы используете.

components/__test__/ClickHandler.test.js

 const clickHandler = jest.fn()

const initialProps = { 
  clickHandler,
  children: <button className="example">Test</button>
  ...other props
};

const wrapper = shallow(<ClickHandler {...initialProps} />);

describe("Example", () => {
   it('handles clicks inside of the component', () => { // this would test the event lisenter, the class method, and the clickHandler -- slightly overkill 
      const spy = jest.spyOn(wrapper.instance(), 'handleClickOutside');

      wrapper.instance().forceUpdate();
      wrapper.find('button').simulate('click');

      expect(spy).toHaveBeenCalled();
      expect(clickHandler).toHaveBeenCalledTimes(0);
      spy.mockClear();
   });

   it('handles clicks outside of the component', () => { // this is a more straight forward test that assumes the event listener is already working
      const event = { target: <div className="example">Outside Div</div> };
      wrapper.instance().handleClickOutside(event);

      expect(clickHandler).toHaveBeenCalled();
   });

})