概要:
我正在尝试测试一个 React 组件,它在其 componentWillMount
中监听原生 DOM 事件。
我发现当涉及到分派事件和添加事件侦听器时,jsdom (@8.4.0
) 的工作不如预期。
我可以提取的最简单的代码片段:
window.addEventListener('click', () => {
throw new Error("success")
})
const event = new Event('click')
document.dispatchEvent(event)
throw new Error('failure')
这会抛出“failure”。
背景:
为了避免上述问题成为 XY 问题,我想提供更多背景信息。
这是我尝试测试的组件的提取/简化版本。您可以在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