There no select class to handle dropdowns in Protractor, we have to use other methods only to select dropdowns

Dropdowns are one of the general elements present in any webpage after buttons and textbars dropdowns are the more frequently available element.

How to select a value in a dropdown in protractor:

  • Find the dropdown using element
  • Click the dropdown
  • Click the option

80% of the dropdowns are single value dropdowns, single value dropdowns are normal dropdowns on which you can select only one value, once you choose a value, the dropdown shrinks.

According to the protractor, there is no difference between standard and custom dropdown.

It was applicable to selenium(java) because they are providing classes to handle standard dropdown but protractor does not have any such helper class in protractor API.

Real-Time example for Dropdown handling:

dropdowns-protractor-typescript

browser.get("https://chercher.tech/practice/dropdowns")
    • Find the dropdown element using the locators and click the dropdown.
// find click the dropdown
element(by.tagName("select#first")).click();
    • Find the dropdown target option using locators, most of the time you should try to find the option with the help of a parent element(dropdown)
// click the option which has value='Yahoo'
element(by.css("#first [value='Yahoo']")).click();
  • Click the dropdown option using the click method.

Complete program for handling dropdown in protractor.

import { browser, element, by} from 'protractor'
describe('Protractor Typescript Demo', function() {
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Excel File Operations', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		browser.get("https://chercher.tech/practice/dropdowns")
		// find click the dropdown
		element(by.tagName("select#first")).click();
		// add sleep to give a time for te options to reveal
		browser.sleep(1000)
		// click the option which has value='Yahoo'
		element(by.css("#first [value='Yahoo']")).click();
	});
});

select-dropdown-protractor

If you are looking only just to handle dropdown then the above one is the answer and that is enough for day-to-day work, so no need to read the below topics.

But if you are a person who wants to learn things for future purposes, then the below topics are for you.

Exceptions in Typescript

Create Select class in Protractor Typescript

Select class is nothing but a class name; you can even say it as a Dropdown class or IDonotCare class.

The reason why I say it as Select class is, in selenium webdriver(Java) we have a class called Select class which handles the standard dropdowns, so I going to name my class to have the standard.

If you name the class as like in other languages, people would understand the usage of it based on the name itself.

Select Class :

The Select class handles the standard single dropdowns and multiple dropdowns with methods present in the Select class. In the below topics, we would be exploring how to create methods to handle the single value dropdowns.

Methods Present in Select Class ( In our Select class )

  • selectByIndex(index:number)
  • selectByValue(String value)
  • selectByVisibleText(String text)
  • getOptions()
  • getSelectedOption()
  • isMultiple()

Working with protractor and Typescript

selectByIndex(index:number)

Select by the index is nothing but selecting an option present in the dropdown based on their position in the dropdown.

In Java, the position starts from 0, but as we are creating our own method, so it is up to us to give the index, but I would suggest sticking with the standard. So we also will be starting the index from 0.

Please do not refer to the UI of the dropdown; we just need to use HTML source code only, not the UI. select-by-index-protractor

For this purpose we have to create a Typescript class called Select in Select.ts file, Please do forgive if you feel like why does he explaining from very basic.

Steps to create Select class Constructor

    • Create a file called select.ts and create a class inside the file named Select.
export class Select {
    • Create a global variable called dropdown of ElementFinder type
// dropdown
dropdown:ElementFinder;
    • Create a constructor for the select class, which accepts a parameter of ElementFinder type.
//constructor  accepts dropdown as element
constructor(dropdownElement:ElementFinder) {
    • Assign the received element to the global variable dropdown.
// assign block variable to the global variable
this.dropdown = dropdownElement;
    • Click the element received in the constructor.
// click the dropdown
dropdownElement.click()
  • Add some sleep for the dropdown to reveal it's options.

Steps to create selectByIndex(index:number)

    • Create a method called selectByIndex(), and it should accept a number parameter
public selectByIndex(index:number){
    • We have to add 1 with the received index even though select option starts with 0; we cannot find elements with 0 index in XPath and CSS selector. what I mean is Xpath's and CSS selector's index starts with 1
index = index + 1;
    • Now try to find the inner element of an element as we learned before starting the Select class.
    • Click the inner element.
// select the option
this.dropdown.element(by.css("option:nth-child("+index+")")).click()
    • If somebody is Xpath lover, then please use the XPath below rather than above CSS selector
// select the option
this.dropdown.element(by.xpath("//option["+index+"]")).click()
//select.ts
import {browser, by, ElementFinder } from "protractor";
export class Select {
    // dropdown
    dropdown:ElementFinder;
    //constructor  accepts dropdown as element
    constructor(dropdownElement:ElementFinder) {
		// assign block variable to the global variable
       this.dropdown = dropdownElement;
       // click the dropdown
       dropdownElement.click()
       browser.sleep(1000)
    }
    public selectByIndex(index:number){
        index = index + 1;
        console.log("Selecting element based index : "+index)
        // select the option
        this.dropdown.element(by.css("option:nth-child("+index+")")).click()
    }
 }


Why do we need a Constructor in this case:

  • To initialize all the non-static elements in the class
  • To accept the element once and to supply the same element to all the methods, so that methods will not expect the element every time we call them.
  • To call the non-static methods, all the methods in our select class are non-static

Test the selectByIndex() Method :

We have created our Select class now lest create the test cases using describe & it block using Jasmine.

  • Create describe and it block
  • Set this URL is not an angular app.
  • Open the URL of the app.
  • Find the dropdown element, which will be in the ElementFinder type.
  • Create an object to the Select class using constructor and pass the dropdown element as a parameter
  • Call the selectByIndex() method and pass which index you want to select.
import { browser, element, by, ElementFinder} from 'protractor'
import { Select } from './Select';
describe('Protractor Typescript Demo', function() {
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Excel File Operations', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		browser.get("https://chercher.tech/practice/dropdowns")
		let dropdownEle:ElementFinder = element(by.css("select#first"))
		let sel:Select = new Select(dropdownEle);
		//select the value based on the index
		sel.selectByIndex(3)
	});
});

Handle single iFrame

selectByValue(String value)

selectByValue() method works based on an attribute called value

select-by-value-dropdown-protractor

Almost all the methods are just the trick of CSS selector and XPath, in those methods we will be forming the CSS sector which will find the option based on the value attribute

If we can a method based on the attribute, don't you think we can form the methods based on the other attributes like id, class, name, so on.

We will be using the same class, but below will add code to the select class.

import {browser, by, ElementFinder } from "protractor";
export class Select {
	public selectByValue(value:string){
        console.log("Selecting element based value  : "+value)
        // select the option
        this.dropdown.element(by.css("option[value='"+value+"']")).click()
    }
    // constructor and remaining code
 }

Click an Element

selectByVisibleText

selectByText() method works based on the text present in the element

select-by-text-protractor

In this method, we will be finding the inner element based on the text present in the element.

public selectByVisibleText(visibleText:string){
        console.log("Selecting element based text  : "+visibleText)
        // select the option
        this.dropdown.element(by.xpath("//option[text()='"+visibleText+"']")).click()
    }

getOptions()

getOption method will return all the options present in the dropdown, including default option.

In this method, we will find all the element which has the option as their tag name.

public getOptions(visibleText:string){
	console.log("returning all options  : "+visibleText)
	// return all the options
	this.dropdown.all(by.css("option"))
}

isSelected in Protractor

isMultiple

isMultiple method gives information about the dropdown, whether it is a single value dropdown or multiple value dropdown.

public  isMultiple(visibleText:string){
	console.log("returning all options  : "+visibleText)
	// select the option
	this.dropdown.getAttribute("multiple").then(function(multipleOrNot){
		if(multipleOrNot){
			return true
		}else{
			return false;
		}
	})
}

Learn to handle Upload Pop in Protractor

Select class in protractor

Below is the complete select class that we have built so far, these solely depend on my knowledge only so this is not a standard, but it is one of the ways.

import {browser, by, ElementFinder } from "protractor";
export class Select {
    // dropdown
    dropdown:ElementFinder;
    //constructor  accepts dropdown as element
    constructor(dropdownElement:ElementFinder) {
       this.dropdown = dropdownElement;
       // click the dropdown
       dropdownElement.click()
       browser.sleep(1000)
    }
    public  isMultiple(visibleText:string){
        console.log("returning all options  : "+visibleText)
        // select the option
        this.dropdown.getAttribute("multiple").then(function(multipleOrNot){
            if(multipleOrNot){
                return true
            }else{
                return false;
            }
        })
    }
    public getOptions(visibleText:string){
        console.log("returning all options  : "+visibleText)
        // select the option
        this.dropdown.all(by.css("option"))
    }
    public selectByVisibleText(visibleText:string){
        console.log("Selecting element based text  : "+visibleText)
        // select the option
        this.dropdown.element(by.xpath("//option[text()='"+visibleText+"']")).click()
    }
    public selectByValue(value:string){
        console.log("Selecting element based value  : "+value)
        // select the option
        this.dropdown.element(by.css("option[value='"+value+"']")).click()
    }
    public selectByIndex(index:number){
        index = index+1;
        console.log("Selecting element based index : "+index)
        // select the option
        this.dropdown.element(by.css("option:nth-child("+index+")")).click()
    }
 }

Explicit wait in Protractor

Sendkeys for selecting a value in the dropdown

We can use the sendKeys method to set the value in the dropdown/combo box; we have to provide exact text to be selected in the send keys method.

import { browser, element, by} from 'protractor'
describe('Protractor Typescript Demo', function() {
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Excel File Operations', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		browser.get("https://chercher.tech/practice/dropdowns")
		// set the value using sendkeys
		element(by.tagName("select#first")).sendKeys("Bing");
	});
});

f / x describe

The value selected or not in the dropdown with the protractor

Sometimes you might have come across situations where you have to check whether a particular value in the dropdown is selected or not.

isSelected() helps the user to see whether a value is selected or not in the dropdown, if the value is selected then it will return true otherwise false.

I would recommend you to use the XPath/CSS selector, which related to the dropdown and option like below.

import { browser, element, by} from 'protractor'
describe('Protractor Typescript Demo', function() {
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Excel File Operations', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		browser.get("https://chercher.tech/practice/dropdowns")
		// Check value in dropdown selected or not
		expect(element(by.tagName("select#first option[value='Bing']"))).toBe(true, "Bing is not selected in dropdown")
	});
});

selectByValue in Dropdowns

Different ways to select the dropdown option

Selecting a value from the dropdown is an easier task, but sometimes we may need to select the option without using Select class.

We can select the dropdown values in a few ways:

  • Click method
  • click methods from actions
  • Sendkeys method
  • Javascript method

mouseMove / hover in Protractor

JavaScript method to select the dropdown option

We can use the Javascript method to select an option from the dropdown with the help of JavaScriptExecutor. We have to set the dropdown option using the value property of the element.

1. Open the browser and navigate to URL
2. Find the dropdown
3. Set the value using Javascript executor

import { browser, element, by, ElementFinder} from 'protractor'
describe('Protractor Typescript Demo', function() {
	browser.ignoreSynchronization = true; // for non-angular websites
	it('Excel File Operations', function() {
		// set implicit time to 30 seconds
		browser.manage().timeouts().implicitlyWait(30000);
		browser.get("https://chercher.tech/practice/dropdowns")
		element(by.css("select#first")).then(function(element){
			browser.executeScript("arguments[0].value='Yahoo'", element);
		})
	});
});

Protractor Interview Questions

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Nikhil
    cannot see all drop down topics only first topic is visible
    Reply
  • Reply
  • Mallikarjuna
    Hi Pavan,
    I wanted compare dropdown values with expected list. Please tell me how to compare two list (comparing actual and expected list)
    Thanks,
    Mallik
    Reply
  • Shiva
    hi Karthi,
    I have installed protractor and jasmine and related software but i am getting the below error when i am running the below comment.
    protractor conf.js
    Error is:
    DEPRECATION: Setting randomizeTests directly is deprecated, please use the random option in `configure`
    DEPRECATION: Setting specFilter directly on Env is deprecated, please use the specFilter option in `configure`
    Error: Error while waiting for Protractor to sync with the page: "both angularJS testability and angular testability are undefined
    Reply
    • ++ Below are my conf.js files
      conf.js:
      // An example configuration file.
      exports.config = {
        directConnect: true,
        // Capabilities to be passed to the webdriver instance.
        capabilities: {
          'browserName': 'firefox',
          	SELENIUM_PROMISE_MANAGER: false
        },
        // Framework to use. Jasmine is recommended.
        framework: 'jasmine',
        // Spec patterns are relative to the current working directory when
        // protractor is called.
        specs: ['spec.js'],
        // Options to be passed to Jasmine.
        jasmineNodeOpts: {
          defaultTimeoutInterval: 30000,
         // SELENIUM_PROMISE_MANAGER : true,
      	}
      };
      Could you please help me on this.
      
      Reply
      • Reply
  • Ritika
    How to handle a dropdown which do not shrinks after selecting a value in protractor?
    Reply
    • karthiQ [ admin]
      Hi Ritika,
      I did not understand your question clearly but this might help you.
      When the dropdown is not shrinking, it may be because of your design( expected) or because dropdown taking a moment to respond. 
      In such cases, try to find an area in your application, clicking there has no affect on page.
      Once you spot such spot, then after selecting dropdown please click there now dropdown should shrink
      
      Reply
      • Sridevi
        Hi, If the background page is not clickable, then how do i handle it? I am meaning to say, when the drop down opens, the modal window behind becomes invisible overlay, which goes to the background. please help
        Reply