摘要:jsdom:dispatchEvent /的addEventListener似乎并没有工作
我试图测试阵营组件侦听本机的DOM事件在其componentWillMount
。
我发现jsdom(@8.4.0
)在调度事件和添加事件侦听器时无法按预期工作。
我可以提取的代码最简单的一点:
window.addEventListener('click',() => {
throw new Error("success")
})
const event = new Event('click')
document.dispatchEvent(event)
throw new Error('failure')
这将引发 “失败”。
语境:
在上述的风险是一个XY problem,我想提供更多的上下文。
这是我试图测试的组件的提取/简化版本。 You can see it working on Webpackbin.
import React from 'react'
export default class Example extends React.Component {
constructor() {
super()
this._onDocumentClick = this._onDocumentClick.bind(this)
}
componentWillMount() {
this.setState({ clicked: false })
window.addEventListener('click', this._onDocumentClick)
}
_onDocumentClick() {
const clicked = this.state.clicked || false
this.setState({ clicked: !clicked })
}
render() {
return <p>{JSON.stringify(this.state.clicked)}</p>
}
}
这是我试图写的测试。
import React from 'react'
import ReactDOM from 'react-dom'
import { mount } from 'enzyme'
import Example from '../src/example'
describe('test',() => {
it('test',() => {
const wrapper = mount(<Example />)
const event = new Event('click')
document.dispatchEvent(event)
// at this point, I expect the component to re-render,
// with updated state.
expect(wrapper.text()).to.match(/true/)
})
})
只是为了完整性,这里是我的test_helper.js
它初始化jsdom:
import { jsdom } from 'jsdom'
import chai from 'chai'
const doc = jsdom('<!doctype html><html><body></body></html>')
const win = doc.defaultView
global.document = doc
global.window = win
Object.keys(window).forEach((key) => {
if (!(key in global)) {
global[key] = window[key]
}
})
繁殖情况:
我这里有一个摄制情况:https://github.com/jbinto/repro-jsdom-events-not-firing
git clone https://github.com/jbinto/repro-jsdom-events-not-firing.git cd repro-jsdom-events-not-firing npm install npm test
'新window.Event( “点击”);'ermagerd。 'doc.createEvent('MouseEvents')。initEvent('click',true,true)'在jsdom中返回undefined ... 1.5hrs以找到您的答案O.o – Larry