Recently, I've noticed a new locator being added to the Protractor documentation - the by.js()
:
Locates an elements by evaluating a JavaScript expression, which may be either a function or a string.
I understand what this locator provides, but I am missing the real-world use cases when this locator can be useful. When should I prefer to use by.js
instead of other built-in locators like by.css
?
I feel the use case is to get elements using core javascript functions, whenever css
and other element locators won't help or are don't have properties that we could use. Scenarios -
browser.executeScript
then by.js
can be used to replace it.Example: -
Suppose if you had to get an element that appears on top between the two, you could get it this way -
var ele = element(by.js(function(){
var ele1 = document.getElementById('#ele1');
var ele2 = document.getElementById('#ele2');
var val = ele1.compareDocumentPosition(ele2);
if(val === 4) return ele1;
else return ele2;
}));
filter
can be used in this case, but by.js
also supports it.Example: -
Suppose if there's element which has :before
and :after
transitions -
.element:before {
color: rgb(255, 0, 0);
}
To verify the color of the element, we could use by.js
passing in a javascript statement to get the element -
var ele = element(by.js(function(){
return window.getComputedStyle(document.querySelector('.element'), ':before');
}));
expect(ele.getCssValue('color')).toEqual('rgb(255, 0, 0)');
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With