javascript - React.addons.TestUtils.Simulate.scroll 不工作

标签 javascript reactjs dom-events jsdom reactjs-testutils

我正在尝试使用 ReactJS 和 JSDOM 模拟滚动事件。

最初我尝试了以下方法:

var footer = TestUtils.findRenderedDOMComponentWithClass(Component, 'footer');
footer.scrollTop = 500;
TestUtils.Simulate.scroll(footer.getDOMNode());
//I tried this as well, but no luck
//TestUtils.Simulate.scroll(footer);

根本不会传播滚动事件。然后,我手动创建了事件并且一切正常:

var evt = document.createEvent("HTMLEvents");
evt.initEvent("scroll", false, true);
element.dispatchEvent(evt);

问题:我在使用 TestUtils 时做错了什么吗?我怎样才能让它发挥作用?

最佳答案

我的情况可能与 OP 的情况不同,但我一直在努力解决类似的问题,经过大量搜索后找到了我的出路。我意识到问题的症结在于 TestUtils.Simulate.scroll() 仅模拟由特定 React 组件分派(dispatch)的滚动事件(例如,当您设置了 overflow: scroll 时在该组件上)而不是 window 调度的滚动事件。

特别是,我试图测试我在 React 类中设置的滚动处理程序,如下所示:

componentDidMount: function () {
    window.addEventListener('scroll', this.onScroll);
},

componentWillUnmount: function () {
    window.removeEventListener('scroll', this.onScroll);
},

为了测试 onScroll(),我最终发现我必须模拟从 window 发送滚动事件,如下所示:

document.body.scrollTop = 100;
window.dispatchEvent(new window.UIEvent('scroll', { detail: 0 }));

这对我很有用。

关于javascript - React.addons.TestUtils.Simulate.scroll 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128178/

相关文章:

javascript - 我想在输入框、表格或使用node.js的div中的.html文件中显示存储在mysql数据库中的数据

javascript - react native 文本颜色不起作用

reactjs - react 日期选择器和 typescript

javascript - 修改Google搜索结果页面

javascript - 无法清除 Angular 中 ngDialog 模板中的表单输入值

javascript - React 路由器呈现空白页面

javascript - <a> 标签上的 onclick 处理程序,找出点击了哪个标签

javascript - Fabricjs - 以编程方式选择对象以立即移动/拖动

javascript - 如何在 JS 中使用数学设置 div 的高度?

reactjs - 在 React/Webpack 应用程序中将节点模块导入到 Web Worker