In situations where traditional CSS and element locators are not sufficient, core JavaScript functions can be used to access elements. This is especially helpful in scenarios such as:
- When retrieving an element with core JavaScript functions for use with
browser.executeScript
, by.js
can serve as a replacement.
For example:
If you need to access an element positioned between two others, you can achieve this using the following method:
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;
}));
- When obtaining an element based on its CSS properties like color or font,
by.js
can also be employed alongside the filter
method.
- In cases where elements cannot be accessed through conventional means such as css or xpath, for instance, pseudo-elements with animations or transitions.
For instance:
If there's an element with :before
and :after
transitions applied:
.element:before {
color: rgb(255, 0, 0);
}
To verify the color of the element, by.js
can be utilized by passing a JavaScript statement to retrieve the element -
var ele = element(by.js(function(){
return window.getComputedStyle(document.querySelector('.element'), ':before');
}));
expect(ele.getCssValue('color')).toEqual('rgb(255, 0, 0)');
This approach can be quite useful in certain testing scenarios.