I am trying to test for a click event causing a page scroll. I am trying this, and it is passing when i remove the click simulation. What am i not doing in the test?
React component
var React = require('react');
module.exports = React.createClass({
onClick: function(e) {
e.preventDefault();
window.scrollTo(0, 0);
},
render: function() {
return (<a href="#" className="back-to-top" onClick={this.onClick}>Back to top</a>);
}
});
Jest Test
global.React = require('react');
var TestUtils = React.addons.TestUtils;
var componentPath = '../React/Components/Footer/BackToTop/BackToTop.jsx';
jest.dontMock(componentPath);
describe("Click Event Handler", function() {
it("should scroll to top of the page", function() {
var Component = require(componentPath);
var domComponent = TestUtils.renderIntoDocument(<Component></Component>);
var anchorNode = TestUtils.findRenderedDOMComponentWithTag(domComponent, 'a');
var expectedY = 0;
var expectedX = 0;
// scroll the window
window.scrollTo(5, 1000);
// click Back to Top
TestUtils.Simulate.click(anchorNode);
var actualY = window.pageYOffset;
var actualX = window.pageXOffset;
expect(actualX).toBe(expectedX);
expect(actualY).toBe(expectedY);
});
});
@lostrouter Did you have any luck with this? I'm trying the same thing. My problem seems to be that window.innerHeight is only 300, so window.scrollTo has no effect.
i didn't get anywhere with this and am falling back to testing in browser.
Thank you for reporting this issue and appreciate your patience. We've notified the core team for an update on this issue. We're looking for a response within the next 30 days or the issue may be closed.
You might be able to just directly set window.scrollTop and window.scrollLeft. If that doesn't work, try Object.defineProperty(window, 'scrollTop', {value: 10, writable: true})
I would do it with a fake container instead of window. That's more testable.
Well, here you have a couple of options...
spyOn(window, 'scrollTo') ( not sure if it is like that with that test framework) and you just check that that method was called with the arguments 0, 0expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
I think the second way is good enough, since you code actually "does not care" about what scrollTo does internally, you just need to test that you are calling that method when the click event happens.
I hope this helps :)
Most helpful comment
You might be able to just directly set
window.scrollTopandwindow.scrollLeft. If that doesn't work, tryObject.defineProperty(window, 'scrollTop', {value: 10, writable: true})