为什么不在dispatchEvent上调用React事件处理程序?

Mis*_*hko 12 reactjs reactjs-testutils

考虑React组件中的以下输入元素:

<input onChange={() => console.log('onChange')} ... />
Run Code Online (Sandbox Code Playgroud)

在测试React组件时,我正在模拟用户更改输入值:

input.value = newValue;
TestUtils.Simulate.change(input);
Run Code Online (Sandbox Code Playgroud)

这会导致'onChange'按预期记录.

但是,当'change'直接调度事件时(我正在使用jsdom):

input.value = newValue;
input.dispatchEvent(new Event('change'));
Run Code Online (Sandbox Code Playgroud)

onChange处理器不叫.

为什么?

我使用的动机dispatchEvent不是TestUtils.Simulate因为TestUtils.Simulate不支持事件冒泡而且我的组件的行为依赖于此.我想知道是否有办法测试事件没有TestUtils.Simulate

rof*_*rol 9

没有的一种方法ReactTestUtils.Simulate:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://unpkg.com/react-trigger-change/dist/react-trigger-change.js';
document.head.appendChild(script);
input.value = value;
reactTriggerChange(input);
Run Code Online (Sandbox Code Playgroud)

看看反应触发变化来源,只需挑选所需的东西.示例代码段:

if (nodeName === 'select' ||
    (nodeName === 'input' && type === 'file')) {
    // IE9-IE11, non-IE
    // Dispatch change.
    event = document.createEvent('HTMLEvents');
    event.initEvent('change', true, false);
    node.dispatchEvent(event);
  }
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这个对我有用! (2认同)

Sca*_*ize 6

React使用自己的事件系统SyntheticEvents(防止浏览器不兼容,并对事件做出更多控制).

使用TestUtils正确创建会触发您的onChange侦听器的事件.

dispatchEvent另一方面,该功能将创建"本机"浏览器事件.但是你拥有的事件处理程序是通过反应来管理的,因此只会做出反应(badumts)来做出反应SyntheticEvents.

你可以在这里阅读反应事件:https://facebook.github.io/react/docs/events.html