How to globally add custom locator in Protractor?

I wrote a custom locator for Protractor that finds anchorelements by their value ui-sref. In my specs, I just used by.addLocatorto add a custom locator, but I decided that this could be a cool post, and other people use it.

The goal is to add this custom locator to the global Protractor object so that it can be used in any of your specifications.

My initial approach was to add this functionality to the onPrepareProtractor configuration block . Something like pseudo code below:

onPrepare: function () {
  require('ui-sref-locator')(protractor); // The protractor object is available here.
}

This require statement will simply execute this function:

function (ptorInstance) {
  ptorInstance.by.addLocator('uiSref', function (toState, opt_parentElement) {
    var using = opt_parentElement || document;
    var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
    var result = undefined;

    if (possibleAnchors.length === 0) {
      result = null;
    } else if (possibleAnchors.length === 1) {
      result = possibleAnchors[0];
    } else {
      result = possibleAnchors;
    }

    return result;
  });
};

, by protractor, onPrepare. , .addLocator.

+4
2

:

function () {
  by.addLocator('uiSref', function (toState, opt_parentElement) {
  ...

By .

+4

protractor, onPrepare, By. By addLocator. JavaScript , , console.log 'ed protractor.By {}, for (var propName in protractor.By), "" . .

:

onPrepare: function () {
  require('ui-sref-locator')(protractor); // The protractor object is available here.
}

:

function (ptor) {
  ptor.By.addLocator('linkUiSref', function (toState, opt_parentElement) {
    var using = opt_parentElement || document;
    var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
    var result = undefined;

    if (possibleAnchors.length === 0) {
      result = null;
    } else if (possibleAnchors.length === 1) {
      result = possibleAnchors[0];
    } else {
      result = possibleAnchors;
    }

    return result;
  });
};
+3

Source: https://habr.com/ru/post/1546352/


All Articles