本文介绍了单元测试 React 单击组件外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用这个答案中的代码解决在组件外点击的问题:
Using the code from this answer to solve clicking outside of a component:
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
}
}
我不知道如何对不愉快的路径进行单元测试,这样警报就不会运行,到目前为止我得到了什么:
I can't figure out how to unit test the unhappy path so the alert isn't run, what i've got so far:
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
ing 一个节点并发送(不模拟event.target
).simulate
ingclick
里面的元素(不触发事件监听器)
- sending through
wrapper.html()
.find
ing a node and sending through (doesn't mock aevent.target
).simulate
ingclick
on an element inside (doesn't trigger event listener)
我确定我遗漏了一些小东西,但我在任何地方都找不到这样的例子.
I'm sure i'm missing something small but I couldn't find an example of this anywhere.
推荐答案
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上的酶问题的解决方案.
The solution from this enzyme issue on github.
这篇关于单元测试 React 单击组件外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!