Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.addons.TestUtils.Simulate.scroll is not working

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?

like image 318
Alan Souza Avatar asked May 08 '15 16:05

Alan Souza


2 Answers

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.

like image 139
robwhess Avatar answered Oct 18 '22 15:10

robwhess


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 });
like image 45
Jakemmarsh Avatar answered Oct 18 '22 15:10

Jakemmarsh