编程语言
首页 > 编程语言> > javascript – 单元测试React单击组件外部

javascript – 单元测试React单击组件外部

作者:互联网

使用this answer中的代码解决组件外部的点击:

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()发送
> .finding节点并发送(不模拟event.target)
> .simulateing点击里面的元素(不触发事件监听器)

我确定我错过了一些小东西,但我无法在任何地方找到这样的例子.

解决方法:

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()
})

来自this酶的解决方案在github上发布.

标签:enzyme,javascript,unit-testing,reactjs,jestjs
来源: https://codeday.me/bug/20191005/1855289.html