Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test an element is in viewport with protractor

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?

like image 336
Robert T. Avatar asked Oct 17 '22 05:10

Robert T.


1 Answers

First idea (which you mentioned):

  • create class MyRect extend DOMRect
  • create function getBoundingClientMyRect base on getBoundingClientRect
  • create function getWindowMyRect base on (0, 0, wWidth, wHeight) let wHeight = window.innerHeight || document.documentElement.clientHeight; let wWidth = window.innerWidth || document.documentElement.clientWidth;
  • create method isInsideMyRect in MyRect - base on https://gist.github.com/davidtheclark/5515733
  • create method isPartOfMyRect in MyRect - base on https://gist.github.com/davidtheclark/5515733#gistcomment-2113166

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
like image 157
Paweł Avatar answered Oct 21 '22 00:10

Paweł