Javascript React.addons.TestUtils.Simulate.scroll不工作
我试图用ReactJS和JSDOM模拟一个滚动事件 最初,我尝试了以下方法:Javascript React.addons.TestUtils.Simulate.scroll不工作,javascript,javascript-events,reactjs,jsdom,reactjs-testutils,Javascript,Javascript Events,Reactjs,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.scr
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有什么问题吗?我怎样才能做到这一点
Alan从和判断,我相信TestUtils通过WheelEvent
模拟滚动,这意味着它需要deltaY
参数来知道滚动的距离。看起来是这样的:
TestUtils.Simulate.scroll(footer.getDOMNode(), { deltaY: 500 });
componentDidMount: function () {
window.addEventListener('scroll', this.onScroll);
},
componentWillUnmount: function () {
window.removeEventListener('scroll', this.onScroll);
},
document.body.scrollTop = 100;
window.dispatchEvent(new window.UIEvent('scroll', { detail: 0 }));
我的情况可能和OP的不同,但我也遇到了一个类似的问题,经过无数次的搜索,我终于找到了自己的路。我意识到问题的症结在于
TestUtils.Simulate.scroll()
只模拟特定React组件调度的滚动事件(例如,当您在该组件上设置了溢出:scroll
时),而不是窗口调度的滚动事件
特别是,我试图测试在React类中设置的滚动处理程序,如下所示:
TestUtils.Simulate.scroll(footer.getDOMNode(), { deltaY: 500 });
componentDidMount: function () {
window.addEventListener('scroll', this.onScroll);
},
componentWillUnmount: function () {
window.removeEventListener('scroll', this.onScroll);
},
document.body.scrollTop = 100;
window.dispatchEvent(new window.UIEvent('scroll', { detail: 0 }));
为了测试onScroll()
,我最终发现我必须模拟从窗口调度一个滚动事件,如下所示:
TestUtils.Simulate.scroll(footer.getDOMNode(), { deltaY: 500 });
componentDidMount: function () {
window.addEventListener('scroll', this.onScroll);
},
componentWillUnmount: function () {
window.removeEventListener('scroll', this.onScroll);
},
document.body.scrollTop = 100;
window.dispatchEvent(new window.UIEvent('scroll', { detail: 0 }));
这对我来说非常有效。实际上,这是一个虚惊一场。它不起作用。未传播该事件。