Reactjs 如何使用酶反应调用函数内的事件目标

Reactjs 如何使用酶反应调用函数内的事件目标,reactjs,enzyme,Reactjs,Enzyme,如何调用handleClickOutside函数。我应该如何在这里模仿ClickOut?请帮忙 componentWillUnmount() { document.removeEventListener('click', this.handleClickOutside); } /** * Set the wrapper ref */ setWrapperRef(node) { this.wrapperRef = node;

如何调用
handleClickOutside
函数。我应该如何在这里模仿ClickOut?请帮忙

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

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

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

假设这是一个
HOC
render prop
,将其他组件呈现为
子组件(
this.props.children
)--下面是一个
Jest
Enzyme
测试,因此它可能与您正在使用的略有不同

components/\uuuuu test\uuuu/ClickHandler.test.js

 it('lets click outside and close dropdown', () => {
        const handleClickOutside = sinon.spy();
        expect(handleClickOutside.called).to.be.true;
        wrapper.unmount();
    });
constclickhandler=jest.fn()
常量initialProps={
clickHandler,
儿童:测试
…其他道具
};
常量包装器=浅();
描述(“示例”,()=>{
它('handles clicks in the component',()=>{//这将测试事件lisenter、类方法和clickHandler——有点过火
const spy=jest.spyOn(wrapper.instance(),'handleClickOutside');
wrapper.instance().forceUpdate();
wrapper.find('button').simulate('click');
期望(间谍)。已被调用();
期望(clickHandler).已调用时间(0);
spy.mockClear();
});
它('handles clicks out the component',()=>{//这是一个更直接的测试,假设事件侦听器已经在工作
const event={target:Outside Div};
wrapper.instance().handleClickOutside(事件);
expect(clickHandler).toHaveBeenCalled();
});
})
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();
   });

})