alecxe alecxe - 1 year ago 67
Javascript Question

Locating elements in Protractor vs directly in JavaScript

In one of the tests, I need to scroll into view of an element which can be done via

method parameterizing the script with an element located via Protractor:

var elm = element("myid"));
browser.executeScript("arguments[0].scrollIntoView();", elm.getWebElement());

But, we can also find the element directly via


What is the difference between the two approaches?

is chosen for sample purposes only. The logic inside the script can be more complex.

Answer Source

The first one will tell you explicitly when the element is missing while the second one will raise a JavaScript error saying that null doesn't have the .scrollIntoView method. So to keep the second one maintainable, you need to implicitly handle the case when the element is missing and raise an error with an appropriate message.

The first one is exposed to an unexpected/stale state. The element found by element("myid")) could be removed from the page just before executing browser.executeScript(). The second one is not exposed to this issue since the page is not updated while the script is executed.

The second one is less expensive since it executes one Selenium command (ExecuteScript), while the first one executes two (FindElement and ExecuteScript). Sending a Selenium command to the browser is relatively expensive (minimum of 25ms) and might become significant with multiple calls.

Both will produce the exact same result and will end up calling the same API on the browser side.