小编典典

单元测试React click外部组件

reactjs

使用此答案中的代码来解决在组件外部单击的问题:

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在元件内部(不触发事件侦听器)

我确定我缺少一些小东西,但是我在任何地方都找不到这样的例子。


阅读 234

收藏
2020-07-22

共1个答案

小编典典

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上。

2020-07-22