paint-brush
The Complete Guide Using To Selenium Locators In Protractor To Run Test Automation With Scriptsby@kritikam
121 reads

The Complete Guide Using To Selenium Locators In Protractor To Run Test Automation With Scripts

by Kritika MurariMarch 3rd, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Selenium locators in Protractor are important for running your test automation scripts. Read now to know more about these locators.

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - The Complete Guide Using To Selenium Locators In Protractor To Run Test Automation With Scripts
Kritika Murari HackerNoon profile picture

While testing the functionality for your website, especially web elements such as radio buttons, text boxes, drop-down, etc., you need to make sure that you are able to access these elements. Selenium locators serve this exact purpose: by using this command we can identify these web elements, DOM (Document Object Model), to perform Selenium test automation through our scripts.

These Selenium locators are vital for scripting as if they’re wrong, your automation scripts won’t work. Thus your Selenium test automation efforts rely on these Selenium locators in any testing framework. Protractor, an Angular JS framework, has many Selenium locators that can be identified by using a specific By method during runtime.

In this protractor testing tutorial, we will discuss the Selenium locators in Protractor in-depth and how we can use locators to interact with the application and fetch the current running state. So, let’s get started.

What Is The Importance Of Selenium Locators In Protractor?

Let’s start our protractor testing tutorial by discussing various features that should be kept in mind when choosing a locator with respect to its performance. The Selenium locators in Protractor have proven to be good and reliable in most scenarios. Some of the features that it provides are:

1. Good Readability:

The Selenium locators in the protractor are easily readable and accessible. The locators offer enough flexibility to the test code by making it accessible to the user.

2. Less Maintenance:

  • The Selenium locators in protractors are developed in an optimized manner and hence, they require less maintenance overhead.
  • The structure of the locator is designed in a great fashion so that there is no need to update the locator even when there is a change in the location of the element. It requires modification only if there is any change in the functionality of the web application.

3. Improved Speed:

This is one of the most important properties of the Selenium locators as this feature determines the performance of the web application. The Selenium locators in the protractor have a unique id which makes them relatively faster than other Selenium locators. Sometimes, the speed of locating an element is also dependent on the internal processing speed of the browsers.

The Objective of Selenium Locators in Protractor

Moving on with our protractor testing tutorial, we’ll discuss the importance of Selenium locators. The important point to remember in order to write good end-to-end tests in Protractor is discovering the proper Document Object Model (DOM) elements for the web pages. It tends to globally export the locator factories through the instantiated objects.

Since the protractor is built upon Selenium interfaces, the Selenium locators in the protractor are quite comparable and similar to the ones associated with Selenium WebDriver. Therefore, it’s interesting to know that the framework supports Selenium locators in protractors as well along with its own.

Working of Selenium Locators in Protractor

Next, in this protractor testing tutorial, we’ll discuss how Selenium locators work in Protractor. The way the locator functions in Protractor is by exporting a global function i.e. ‘element’, which inputs the locator and provides us with the ElementFinder in return.

The ElementFinder, on the other hand, offers a fundamental way to communicate with an element and get details about the same with various action methods such as getText(), click(), and sendKeys(). These methods are quite popular and are used frequently when executing Selenium test automation.

The main purpose of the ‘element’ function is to locate a single element. To locate multiple elements, the ‘element.all’ the function is used.

There are several other means by which we can find the elements in Protractor and by using elements locating strategies in Angular JavaScript framework such as by.model(), by.repeater(), by.binding(), etc.

List of Selenium Locators in Protractor

Now in this section of the Protractor testing tutorial, let’s get familiar with global variables that are majorly used in locating the DOM elements with examples for a better understanding of these Selenium locators in Protractor. These are a group of element locator strategies that are associated with the “by” keyword such as by.className, by.css, by.model, etc. Some of the most commonly used are:

  • by.className
  • by.id
  • by.CSSby
  • by.linkText
  • by.name
  • by.partialLinkText
  • by.tagName
  • by.xpath

1. by.className

The className locator is one of the most widely used Selenium locators in Protractor. ts objective is to check for the elements in the page with a class attribute and then further classify the elements specific to their class name.

For Example:

Sample XML Document :-

/* The list contains a class for positive or negative */
 
<ul class="digits">
  <li class="positive">5</li>
  <li class="negative">-6</li>
</ul>

Locator Used:-

/* The locator that returns the expected element for the specified class */
 
var even = browser.findElement(by.className(positive));
expect(even.getText()).toBe('5');
// making use of our locator in our test script //
expect(browser.findElement(by.className('even'))).toBe('-6');

2. by.id

The Id locator is used to discover an element in the web page based on the id attribute defined in the XML document structure.

For Example:

Sample XML Document :-

/* The list contains class for positive or negative */
 
<ul class="digits">
  <li class="negative">-6</li>
  <li class="positive" id="positiveNumber">5</li>
</ul>

Locator Used:-

/* The locator that returns the expected element for the specified id */
 
// making use of our locator in our test script //
var positive = browser.findElement(by.id('positiveNumber'));
expect(positive.getText()).toBe('5');

3. by.css

The CSS locator assists in identifying the elements and classify them based on the CSS selector i.e. the identifier value used to distinguish the element existing on the web page. These Selenium locators are also one of the most preferred substitutes in protractor when we do not have a choice to select based on class name or id.

For Example:

Sample XML Document :-

/* The list contains class for two color i.e blue or red */
 
<ul class="color">
  <li class="first">blue</li>
  <li class="second" id="secondColor">red</li>
</ul>

Locator Used:-

/* The locator that returns the expected element for the specified CSS */
 
var first = browser.findElement(by.css('.first'));
expect(first.getText()).toBe('blue');
// making use of our locator in our test script //
expect(browser.findElement(by.css('#secondColor'))).toBe('red');

4. by.linkText

The objective of the linkText locator is to identify the matching string text corresponding to the anchor element i.e. < a > tag in the DOM. It works only on the hyperlink and by default, the first link text is selected if there are multiple elements present for the link text on the web page.

For Example:

Sample XML Document :-

/* The anchor tag which contains the website name and its URL */
 
<a href="http://www.lambdatest.com">LambdaTest</a>
 
<a href="http://www.lambdatest.com">LambdaTest</a>

Locator Used:-

/* The locator that returns the expected element for the link i.e. Lambda Test*/
 
// making use of our locator in our test script //
var myLink = element(by.linkText(‘LambdaTest'));
 
expect(myLink.getTagName()).toBe('a');

5. by.name

The name locator is used to discover the element having the specific value in the name attribute.

For Example:

Sample XML Document :-

/* The list contains a class for two names i.e John and Mark */
 
<ul>
 
  <li name="developer">John</li>
 
  <li name="tester">Mark</li>
 
</ul>

Locator Used:-

/* The locator that returns the expected element for the specified name */
 
// making use of our locator in our test script //
var developer = browser.findElement(by.name('developer'));
 
// making use of our locator in our test script //
var tester = browser.findElement(by.name('tester'));
 
expect(developer.getText()).toBe('John');
 
expect(tester.getText()).toBe('Mark');

6. by.partialLinkText

The partialLinkText locator is used in scenarios where there is a need to find the elements which contain the string or the portion of the string in the link text element.

For Example:

Sample XML Document :-

/* The list contains anchor tag which has the required text */
 
<ul>
  <li><a href="http://www.lambdatest.com"> Selenium test automation Cloud</a></li>
  <li>Online Selenium Grid for Automated Testing</li>
</ul>

Locator Used :-

// /* The locator that returns the expected element i.e. gives us the 'a' element value ‘Selenium test automation Cloud’ and navigates to the same link */
 
// making use of our locator in our test script //
var myLink = browser.findElement(by.partialLinkText('Cloud'));
 
myLink.click();

7. by.tagName

The tagName locator is used to locate elements having a specific tag name. It looks for elements in the web page having any tag name like < a > , < div > , < p > etc. It functions similar to that of the getElementsByTagName function used in the XML document structure.

For Example:

Sample XML Document :-

/* The list contains anchor tag which has the required text */
 
<a href="http://www.lambdatest.com">LambdaTest</a>

Locator Used :-

// /* The locator that returns the expected element i.e. gives us the 'a' tag  value and that matches with the text given */ //
 
// making use of our locator in our test script //
expect(element(by.tagName('a')).getText()).toEqual('LambdaTest');

8. by.xpath

The Xpath locator is used to find the matching element for the XML Xpath Selector provided. An important thing to note when dealing with XPath Selenium locators is that to search and element the entire XML document model we must we begin our XPath locator with “//”

For Example:

 XPath = //*[ @ value='Inbox'] - matches with Inbox
xpath=//button[ @name="Gma"] - matches with Gmail 

Sample XML Document :-

/* The list contains anchor tag which has the required text */
 
<ul>
  <li><a href="http://www.lambdatest.com">Selenium test automation Cloud </a> </li>
  <li> Online Selenium Grid for Automated Testing </li>
</ul>

Locator Used:-

// /* The locator that returns the expected element i.e. gives us the 'a' tag  value with the help of XPath and that matches with the text given */
 
// making use of our locator in our test script //
var xpathEle = browser.findElement(by.xpath('//ul/li/a'));
 
expect(xpathEle.getText()).toBe(‘Selenium test automation Cloud’);


Angular Specific Selenium Locators

Now, in this protractor testing tutorial, let us have a look at some of the Selenium locators that are used in Angular but are also available for the Protractor framework.

  • by.model
  • by.buttonText
  • by.partialButtonText
  • by.exactBinding
  • by.binding
  • by.exactRepeater
  • by.repeater
  • by.cssContainingText
  • by.options
  • by.deepCss
  • by.addLocator

1. by.model

The model locator identifies the element having the exact text associated with the ng-model attribute.

For Example:

Sample XML Document :-

// /* The XML input type contains the text with the model attribute */ //
 
<input type="text" ng-model="developer.name">
 

Locator Used:-

// /* The locator finds the element with the model attribute and returns the value */ //
 
// making use of our locator in our test script //
element(by.model('developer.name')).click();

2. by.buttonText

The buttonText locator finds a match with an element having the same text of the button tag or inside the sub-element of the tag.

For Example:

Sample XML Document :-

// /* The XML contains the button with the required value */ //
 
<button> Selenium test automation Cloud </button>

Locator Used:-

// /* The locator finds the element with the button tag and returns the value */ //
 
// making use of our locator in our test script //
element(by.buttonText('Selenium test automation Cloud'));

3. by.partialButtonText

The partialButtonTextlocator finds a match with an element that contains the part of the text i.e. partial match in the button tag or inside the sub-element of the tag.

For Example:

Sample XML Document :-

// /* The XML contains the button with the required value */ //
 
<button> Selenium test automation Cloud </button>

Locator Used:-

// /* The locator finds the element with the button tag and returns the value */ //
 
// making use of our locator in our test script //
element(by.partialButtonText('Cloud'));

4. by.exactBinding

The exactBinding locator is used to locate the ng-bind attribute with the exact string/text value provided. It will not check for any partial matches in the text.

For Example:

Sample XML Document :-

// /* The XML input type contains the text with the bind attribute */ //
 
<p ng-bind="developer.name"></p>

Locator Used:-

// /* The locator finds the element with the bind attribute and returns the value */ //
 
// making use of our locator in our test script //
expect(element(by.exactBinding('developer.name')).isPresent()).toBe(true);

5. by.binding

This binding locator is used to locate the ng-bind attribute with the given text value. It also helps in locating the text that is a partial match, i.e. if there is an attribute that has some matching with a given locator then this element will be found by our locator, so the relevant matching elements are returned.

For Example:

Sample XML Document :-

// /* The XML input type contains the text with the bind attribute */ //
 
<p ng-bind="developer.name">John</p>

Locator Used:-

// /* The locator finds the element with the bind attribute and returns the value */ //
 
// making use of our locator in our test script //
var eleName = element(by.binding(developer));
expect(eleName.getText()).toBe('John');

6. by.exactRepeater

The exactRepeater locator identifies the element having the exact text associated with attribute ng-repeat. It will not check for any partial matches in the text.

For Example:

Sample XML Document :-

// /* The XML input type contains the text with the bind attribute */ //
 
<li ng-repeat="dev in developer_names"></li>
 
<li ng-repeat="test in tester_names"></li>

Locator Used:-

// /* The locator finds the element with the bind attribute and returns the exact value */ //
 
// making use of our locator in our test script //
 
expect(element(by.exactRepeater('dev in developer_names')).isPresent()).toBe(true);
 

7. by.repeater

The repeater locator is used to find the element that has the attribute ng-repeat. It also helps in locating the text that is a partial match, i.e. if there is an attribute that has some matching with a given locator then this element will be found by our locator, so the relevant matching elements are returned.

For Example:

Sample XML Document :-

// /* The XML input type contains the text with the repeater attribute */ //
 
<tr ng-repeat="developer_info">
    <td>{{dev.id}}</td>
    <td>{{dev..name}}</td>
    <td>{{dev.salary}}</td>
</tr>

Locator Used:-

// /* The locator finds the element with the repeater attribute and returns the value */ //
 
// making use of our locator in our test script //
 
var devID = element(by.repeater('developer_info').row(0));
expect(devID.getText()).toBe('2');
 
var devName = element(by.repeater('developer_info').row(1));
expect(devName.getText()).toBe('Mark');

8. by.cssContainingText

The cssContainingText locator finds the element by CSS having the specific text string, i.e. it combines the function of the CSS locator and the text element locator to identify the element.

For Example:

Sample XML Document :-

// /* The XML input type contains the text with the css text */ //
 
<ul>
  <li class="color">Blue</li>
  <li class="color">Red</li>
</ul>

Locator Used:-

// /* The locator finds the element and returns the value for the Blue color but not the Red color */ //
 
// making use of our locator in our test script //
 
var blue = element(by.cssContainingText('.color', 'Blue'));

9. by.options

The options locator identifies the element associated with attribute ng-option.

For Example:

Sample XML Document :-

// /* The XML input type contains the text with the option attribute */ //
 
<select ng-options="Colors options in the custom collection">
  <option value="0">Blue Color</option>
  <option value="1">Red Color</option>
  <option value="2">Green Color</option>
</select>

Locator Used:-

// /* The locator finds the element with the options attribute and returns the value */ //
 
// making use of our locator in our test script //
 
var colorOptions = element.all(by.options('Colors options in the custom collection'));
expect(colorOptions.count()).toEqual(Green);

10. by.deepCss

The deepCss locator in Protractor is used to discover the shadow DOM elements, which by default is not easily discoverable by using standard element Selenium locators.

For Example:

Sample XML Document :-

// /* The XML input type contains the text and returns the fetched value */ //
 
<div>
  <span id="outerspan">   //outerspan
  <"shadow tree">           //shadow tree
    <span id="span1"></span>
    <"shadow tree">
      <span id="span2"></span>
    </>
  </>
</div>

Locator Used:-

// /* The locator finds the element with the options attribute and returns the value */ //
 
// making use of our locator in our test script //
 
var mySpan = element.all(by.deepCss('span'));  //myspan
expect(mySpan.count()).toEqual(7);
// making use of our locator in our test script //
 
var checkSpans = element.all(by.css('span');  //verify span
expect(checkSpans.count()).toEqual(5);

In this next section of the Protractor testing tutorial, we’ll discuss how you can integrate Protractor with other powerful tools. Before that, if you want to set up a protractor to run your Selenium automation scripts you can check out our support documentation.

11. by.addLocator

The addLocator in protractor is used to create custom locators and load them later in config.

For Example:

Sample XML Document :-

// /* The XML input type contains the text and returns the fetched value */ //
 
<button ng-click="viewResults()">View</button>

Locator Used:-

// /* The locator finds the element with the options attribute and returns the value */ //
 
// making use of our locator in our test script //
 
by.addLocator('Selenium Grid',function(buttonText, opt_parentElement, opt_rootSelector) {
var using = opt_parentElement || document,
buttons = using.querySelectorAll(‘Automate testing’);
return Array.prototype.filter.call(buttons, function(button) {
return button.textContent === buttonText;
});
});

Integrating Protractor with LambdaTest For Faster Selenium Test Automation

When performing Selenium test automation, we always look for ways that can help us increase our test coverage and improve our test cases. Protractor framework also has the capability to integrate with multiple tools and platforms such as Git, Jenkins, LambdaTest, etc.

The best part of integrating your Protractor scripts with LambdaTest can help you ditch the hassle of maintaining an in-house Selenium infrastructure as you can run your scripts over a cloud-based Selenium Grid of 2000 + real browsers for both desktop and mobile. To integrate Protractor with our online Selenium Grid, you won’t have to make any changes to your specification files. All you need to do is tweak the config file a little to specify the hub details and access key required to connect to Remote WebDriver for our online Selenium Grid. T

Therefore, when it is coupled with the internal capabilities of Protractor, it provides better flexibility to manage our tests and executing parallel Selenium test automation which will exponentially boost our testing execution speed.

Conclusion

As we have seen in this Protractor testing tutorial, that since Protractor is built upon Selenium and mostly used for Angular websites, it inherits properties from them. This is the reason we use Selenium locators in protractor, and it adds more charm to the framework and makes it more robust when used to the fullest. On the other hand, Protractor is not just about Selenium locators there are many other aspects and features of the protector testing available for use in the market which adds more, that we will cover eventually in our protractor testing tutorials.

Previously published at https://www.lambdatest.com/blog/selenium-locators-in-protractor/