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?
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With