我正在尝试使用 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/