csi*_*ilk 20 javascript unit-testing reactjs jestjs enzyme
使用此答案中的代码来解决组件外部的单击:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何对不愉快的路径进行单元测试以便警报不会运行,到目前为止我得到了什么:
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)
})
Run Code Online (Sandbox Code Playgroud)
我试过了:
wrapper.html().find一个节点并通过发送(不嘲笑event.target).simulate荷兰国际集团click的元件上内(不会触发事件侦听器)我确定我错过了一些小东西,但我无法在任何地方找到这样的例子.
quo*_*Bro 23
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()
})
Run Code Online (Sandbox Code Playgroud)
来自这种酶的解决方案在github上发布.
| 归档时间: |
|
| 查看次数: |
8197 次 |
| 最近记录: |