【发布时间】:2016-04-22 21:41:04
【问题描述】:
总结:
我正在尝试测试一个在其componentWillMount 中侦听本机 DOM 事件的 React 组件。
我发现 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
【问题讨论】:
-
很棒的问题结构 + repo
标签: javascript testing jsdom