使用此答案中的代码来解决在组件外部单击的问题:
componentDidMount() { document.addEventListener('mousedown', this.handleClickOutside); } componentWillUnmount() { document.removeEventListener('mousedown', this.handleClickOutside); } setWrapperRef(node) { this.wrapperRef = node; } handleClickOutside(event) { if (this.wrapperRef && !this.wrapperRef.contains(event.target)) { this.props.actions.something() // Eg. closes modal } }
我不知道如何对不愉快的道路进行单元测试,以使警报不会运行,到目前为止,我得到了什么:
it('Handles click outside of component', () => { props = { actions: { something: jest.fn(), } } const wrapper = mount( <Component {... props} />, ) expect(props.actions.something.mock.calls.length).toBe(0) // Happy path should trigger mock wrapper.instance().handleClick({ target: 'outside', }) expect(props.actions.something.mock.calls.length).toBe(1) //true // Unhappy path should not trigger mock here ??? expect(props.actions.something.mock.calls.length).toBe(1) })
我试过了:
wrapper.html()
.find
event.target
.simulate
click
我确定我缺少一些小东西,但是我在任何地方都找不到这样的例子。
import { mount } from ‘enzyme’ import React from ‘react’ import ReactDOM from ‘react-dom’
it('Should not call action on click inside the component', () => { const map = {} document.addEventListener = jest.fn((event, cb) => { map[event] = cb }) const props = { actions: { something: jest.fn(), } } const wrapper = mount(<Component {... props} />) map.mousedown({ target: ReactDOM.findDOMNode(wrapper.instance()), }) expect(props.actions.something).not.toHaveBeenCalled() })
来自此酶问题的解决方案在github上。