Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is by.js locator for in Protractor/WebDriverJS?

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?

like image 734
alecxe Avatar asked Apr 26 '16 15:04

alecxe


1 Answers

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 -

  1. If you are getting an element using core javascript functions passing it to 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;
}));
  1. If you want to get element using its css values like color, font, etc... Though filter can be used in this case, but by.js also supports it.
  2. If the elements are not accessible by css or xpath or any other locators, for example pseudo-elements that have animations or transitions.

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.

like image 100
giri-sh Avatar answered Oct 02 '22 05:10

giri-sh