jsdom:dispatchEvent/addEventListener似乎无法工作

14

概要:

我正在尝试测试一个 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

很棒的问题结构 + 存储库 - AndrewMcLagan
3个回答

14

您正在将事件分派到document,因此window将无法看到它,因为默认情况下它不会冒泡。 您需要创建带有bubbles设置为true的事件。 示例:

var jsdom = require("jsdom");

var document = jsdom.jsdom("");
var window = document.defaultView;

window.addEventListener('click', function (ev) {
  console.log('window click', ev.target.constructor.name,
              ev.currentTarget.constructor.name);
});

document.addEventListener('click', function (ev) {
  console.log('document click', ev.target.constructor.name,
              ev.currentTarget.constructor.name);
});

console.log("not bubbling");

var event = new window.Event("click");
document.dispatchEvent(event);

console.log("bubbling");

event = new window.Event("click", {bubbles: true});
document.dispatchEvent(event);

3
new window.Event("click"); 是创建一个模拟点击事件的方法。"ermagerd." 可能是一种表达惊讶或兴奋的方式。在 jsdom 中,使用 doc.createEvent('MouseEvents').initEvent('click', true, true) 方法来代替,但该方法返回 undefined,可能是因为此方法在最新版本的 JavaScript 中已被废弃。您可能需要查找jsdom中其他可用的方法来触发模拟点击事件。 - Larry

7
问题在于jsdom提供的document实际上并未被Enzyme测试使用。
Enzyme使用React.TestUtils中的renderIntoDocument
链接:https://github.com/facebook/react/blob/510155e027d56ce3cf5c890c9939d894528cf007/src/test/ReactTestUtils.js#L85
{
  renderIntoDocument: function(instance) {
    var div = document.createElement('div');
    // None of our tests actually require attaching the container to the
    // DOM, and doing so creates a mess that we rely on test isolation to
    // clean up, so we're going to stop honoring the name of this method
    // (and probably rename it eventually) if no problems arise.
    // document.documentElement.appendChild(div);
    return ReactDOM.render(instance, div);
  },
// ...
}

这意味着我们所有的Enzyme测试都不是针对jsdom提供的“document”执行的,而是针对一个与任何文档分离的div节点执行的。Enzyme仅在静态方法中使用jsdom提供的“document”,比如getElementById等。它不用于存储/操作DOM元素。为了进行这些类型的测试,我决定实际调用ReactDOM.render,并使用DOM方法对输出进行断言。

-1

代码: https://github.com/LVCarnevalli/create-react-app/blob/master/src/components/datepicker

链接: ReactTestUtils.Simulate无法触发通过addEventListener绑定的事件?

组件:

componentDidMount() {   
 ReactDOM.findDOMNode(this.datePicker.refs.input).addEventListener("change", (event) => {
    const value = event.target.value;
    this.handleChange(Moment(value).toISOString(), value);
  });
}

测试:

it('change empty value date picker', () => {
    const app = ReactTestUtils.renderIntoDocument(<Datepicker />);
    const datePicker = ReactDOM.findDOMNode(app.datePicker.refs.input);
    const value = "";

    const event = new Event("change");
    datePicker.value = value;
    datePicker.dispatchEvent(event);

    expect(app.state.formattedValue).toEqual(value);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接