簡體   English   中英

jsdom:dispatchEvent / addEventListener似乎不起作用

[英]jsdom: dispatchEvent/addEventListener doesn't seem to work

摘要:

我試圖在其componentWillMount測試一個偵聽本機DOM事件的React 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問題 ,我想提供更多背景信息。

這是我試圖測試的組件的提取/簡化版本。 你可以在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]
  }
})

復制案例:

我在這里有一個repro案例: 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

您將事件發送到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);

這里的問題是,jsdom提供的document實際上並未被酶測試使用。

Enzyme使用renderIntoDocumentReact.TestUtils

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);
  },
// ...
}

這意味着我們所有的酶測試都不會針對jsdom提供的document ,而是執行與任何文檔分離的div節點。

酶僅使用jsdom提供的document用於靜態方法,例如getElementById等。它不用於存儲/操作DOM元素。

為了進行這些類型的測試,我使用了實際調用ReactDOM.render ,並使用DOM方法在輸出上斷言。

代碼: 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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM