Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 scrollIntoView() method parameterizing the script with an element located via Protractor:

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

But, we can also find the element directly via getElementById():

browser.executeScript("document.getElementById('myid').scrollIntoView();");

What is the difference between the two approaches?

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

like image 925
alecxe Avatar asked Jul 17 '16 13:07

alecxe


People also ask

Which locator is used to locate an element using bind attribute value?

Binding locator is used to locate the element using bind attribute value given.

How do you handle an element not found in a protractor?

The below code will first find an element by Id 'IdTextBoxCode'. Then the code to enter code 'codeTextBox. sendKeys(code);' is in TRY block. If the code throws exception(in this case, if the element with Id 'IdTextBoxCode' is not found), then it will go to the catch block and the error handling function.


1 Answers

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(by.id("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.

like image 134
Florent B. Avatar answered Nov 15 '22 12:11

Florent B.