I have a webpage where there is scroll happening to next section within the webpage on click of a button. Can someone please suggest how to capture that scroll? Code is with in the anchor tag and href is pointing to # to scroll to next section in page. I am not sure how to validate if scroll actually worked?
2 Answers
You could check that the anchor is scrolled at the top of the window by checking the positon relative to the viewport with getBoundingClientRect() :
browser.get('https://www.w3.org/TR/webdriver');
$("[href='#capabilities']").click();
// assert that the position of the anchor relative to the top border of the window is less than 16 pixels.
var anchor = $('#h-capabilities');
var isCloseToTop = browser.executeScript(e => !(e.getBoundingClientRect().top >> 4), anchor);
expect(isCloseToTop).toBeTruthy();
Note that if the anchor is at the very bottom of the document, the anchor will not be at the top of the window, but somewhere within. So you should also consider this case with a more generic solution:
browser.get('https://www.w3.org/TR/webdriver');
$("[href='#informative-references']").click();
expect(isScrolledTop($('#h-informative-references'))).toBeTruthy();
function isScrolledTop(element) {
return browser.executeScript(function(elem) {
var doc = elem.ownerDocument,
viewHeight = doc.defaultView.innerHeight,
docBottom = doc.documentElement.getBoundingClientRect().bottom,
box = elem.getBoundingClientRect();
return box.top > -1 && (box.top < 25 || (docBottom - viewHeight) < 25);
}, element);
}
Comments
You can assert/check few things in this case:
the current URL to point to the correct
#section:expect(browser.getCurrentUrl()).toEqual("https://url.com/mypage#myparagraph");check the
scrollTopposition of thebodyelement (assuming it is what is scrolled - or the other scrollable container):var body = $("body"); expect(body.getCssValue("scrollTop")).toEqual("someValue"); // or apply the "greater than" check- check the current active element (assuming there is an element focused once the "anchor" paragraph is becoming active)
solution based on your suggestion to use
window.pageYOffset- compare the value before and after the click:browser.executeScript('return window.pageYOffset;').then(function (offsetBefore) { offsetBefore = parseInt(offsetBefore); button.click(); browser.executeScript('return window.pageYOffset;').then(function (offsetAfter) { offsetAfter = parseInt(offsetAfter); expect(offsetAfter).toBeGreaterThan(offsetBefore); }); });
6 Comments
pageYOffset value before the click and after and compare the values. Hope that helps.pageYOffset before and after will not work if the link is not already within the window. The driver will scroll it into the view before clicking on it. So the pageYOffset will increase even if the click fails to jump to the reference.