4

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"))
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195

1 Answers1

5

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")
Florent B.
  • 41,537
  • 7
  • 86
  • 101
  • I couldn't implement this in my project. I tried few ways. Do you mind sharing your code, I want to understand how did you add custom locators to global namespace? I always got this error: "$x is not a function". Tried adding element(by.xpath) – Harisha K P May 05 '21 at 19:15