alecxe alecxe - 4 months ago 81
Javascript Question

Adding custom locator shortcuts in Protractor

In Protractor, there are

and
$$
convenient shortcuts
for CSS selectors:

$(".myclass") // means: element(by.css(".myclass"))
$$(".myclass") // means: element.all(by.css(".myclass"))


Is it possible to introduce custom shortcuts for other locators?




To be more specific, what if we want to have a
$r
and
$$r
shortcuts for "by repeater" calls. To be able to write:

$r("item in items")
$$r("item in items")


instead of:

element(by.repeater("item in items"))
element.all(by.repeater("item in items"))

Answer

To create a shortcut, add the custom locator on the global namespace and on the prototype of ElementFinder and ElementArrayFinder:

global.$r = function(selector) {
  return protractor.element(protractor.by.repeater(selector));
};

global.$$r = function(selector) {
  return protractor.element.all(protractor.by.repeater(selector));
};

ElementFinder.prototype.$$r = function(selector) {
  return this.all(protractor.by.repeater(selector));
};

ElementFinder.prototype.$r = function(selector) {
  return this.element(protractor.by.repeater(selector));
};

ElementArrayFinder.prototype.$$r = function(selector) {
  return this.all(protractor.by.repeater(selector));
};

Usage:

$r("item in items")
$$r("item in items")
$("#id").$r("item in items")
$("#id").$$r("item in items")
Comments