Using Locators in Protractor

Finding DOM elements for WebPages is very important and a key to write your end to end tests in Protractor. How to interact with the locators, to get the information for the current state of your application, is what we need to understand here in this article.

This doc is an overview of how to locate and perform actions on DOM elements using Protractor.

Overview

Protractor exports a global function ‘element’ which takes ‘Locator’ and then returns an ‘ElementFinder’. The function ‘element’ is used to locate a single element. However, if you are looking for multiple elements, then you should use ‘element.all’ function.

The ‘ElementFinder’ has a set of action methods such as click (), getText (), and sendKeys. These are well known as they are being commonly used while performing selenium tests. This is the core way to interact with an element and get information back from it.

Locators

A locator tells Protractor how to find a certain DOM element. Protractor exports locator factories on the global by the object. The most common locators are:

//From the image given below, find an element using a css locator

Using Locators in Protractor

It should be by.css(‘.search-query’);

//From the image given below, find an element with the given id

Using Locators in Protractor

It should be by.id(‘angularScript’);

//Finding an element with a certain ng-model as shown below in the image:

Using Locators in Protractor

It should be by.model(‘search.query’);

//Finding an element bound to the given variable as shown in the below example

<span ng-bind=”person.email”></span>

It should be by.binding(‘person.email’);

//Find an element by button text, which can be understood by the below given example

 <button>Save</button> It should be by.buttonText(‘Save’); //Find an element by partial button text as shown in the example given below <button>Save my file</button> 

It should be by.partialButtonText(‘Save’);

//Find elements insight an ng-repeat, as shown below

<div ng-repeat=“cat in pets”</div> 

It should be by.repeater(‘cat in pets’);