React.addons.TestUtils.Simulate.scroll is not working
Asked Answered
A

2

6

I'm trying to simulate a scroll event with ReactJS and JSDOM.

Initially I tried the following:

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);

The scroll event is not propagated at all. Then, I've manually created the event and everything worked fine:

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

Question: Am I doing something wrong with the TestUtils? How can I make that to work?

Allisan answered 8/5, 2015 at 16:2 Comment(0)
P
10

My situation may be different than the OP's, but I was struggling with the a similar problem and found my way here after lots and lots of searching. I realized the crux of my problem was that TestUtils.Simulate.scroll() only simulates a scroll event dispatched by a specific React component (e.g. when you have overflow: scroll set on that component) and not a scroll event dispatched by window.

In particular, I was trying to test a scroll handler I'd set up in a React class like this:

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

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

To test onScroll(), I finally figured out that I had to simulate dispatching a scroll event from window, like this:

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

That worked great for me.

Paleontology answered 24/1, 2016 at 2:52 Comment(0)
B
3

Judging from this and this, I believe TestUtils simulates the scrolling via a WheelEvent, which means it needs a deltaY parameter to know how far to scroll. That would look like this:

TestUtils.Simulate.scroll(footer.getDOMNode(), { deltaY: 500 });
Bromate answered 8/5, 2015 at 19:46 Comment(1)
Actually this was a false alarm. It did not work. The event did not get propagated.Allisan

© 2022 - 2024 — McMap. All rights reserved.