Test an element is in viewport with protractor

1.2k views Asked by At

I want to test if my app scrolled to a specific post inside a thread page.

Initially I thought isDisplayed might help, and coded something like:

element(by.id(postId)).isDisplayed().then((isDisplayed) => {
  expect(isDisplayed).toBe(true);
});

After a closer reading of the documentation, isDisplayed does not check if an element is inside the viewport.

A hacky way would be to calculate the positions of various elements, starting with the scrollable parent (which is not window in my case).

Is there a best practice for checking this?

1

There are 1 answers

0
Paweł On

First idea (which you mentioned):

el.getWindowMyRect().isInsideMyRect(getWindowMyRect())

This method does not solve the problem with internal scrolls inside the page


Secand Idea:

  • elm.getBoundingClientRect() and note the value
  • scroll to element if need: browser.executeScript("arguments[0].scrollIntoViewIfNeeded();", elm.getWebElement());
  • elm.getBoundingClientRect() - again and compare with previous value if the value has been changed then the scrolling was necessary