Dropdowns

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 more frequently available element.

Steps to select a value in 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 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 doesnot have any such helper class in protractor api.

Real Time example for Dropdown handling:

dropdowns-protractor-typescript
  • Navigate to the : file:///C:/Users/user/Music/Site/protractor/dropdowns-protractor.php
  • 
    browser.get("https://chercher.tech/practice/practice-dropdowns-selenium-webdriver")			
    


  • 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 help of parent element(dropdown)
  • 
    // click the option which has value='Yahoo'
    element(by.css("#first [value='Yahoo']")).click();			
    


  • Click the dropdown option using 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/practice-dropdowns-selenium-webdriver")
		
		// 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 above one is answer and that is enough for day to day work, so no need to read below topics.

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

Create Select class in Protractor Typescript

Select class is nothing but class name, you can even say it as 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 gonna name my class to have the standard.

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

Select Class :

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

Methods Present in Select Class ( In out Select class )

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

selectByIndex(index:number)

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

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

Please donot refer 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 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 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 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 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 a 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 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 out 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 ElementFinder type
  • Create object to the Select class using constructor and pass the dropdown element as 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/practice-dropdowns-selenium-webdriver")
		
		let dropdownEle:ElementFinder = element(by.css("select#first"))
		let sel:Select = new Select(dropdownEle);
		//select the value based on the index
		sel.selectByIndex(3)
	});
});			

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 method 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 same class but below will added 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 
 }			

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 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"))
}			

isMultiple

isMultiple method gives information about the dropdown whether it is 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 depends on my knowledge only so this is not a standard, but it is one of the way.


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()
    }
 }		

Sendkeys for selecting value in dropdown

We can use sendKeys method to set the value in the dropdown/combo box, we have to provide exact text to be selected in 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/practice-dropdowns-selenium-webdriver")
								
								// set the value using sendkeys
								element(by.tagName("select#first")).sendKeys("Bing");
							});
						});			
						

Value selected or not in dropdown with protractor

Sometimes you might have came across situations here you have to check whether a particular value in dropdown is selected or not.

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

I would recommend you to use the xpath/CSS selector which related 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/practice-dropdowns-selenium-webdriver")
								
								// Check value in dropdown selected or not
								expect(element(by.tagName("select#first option[value='Bing']"))).toBe(true, "Bing is not selected in dropdown")
							});
						});			
						

Different ways to select dropdown option

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

We can select the dropdown values in few ways:

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

JavaScript method to select dropdown option

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

1. Open 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/practice-dropdowns-selenium-webdriver")
									element(by.css("select#first")).then(function(element){
										browser.executeScript("arguments[0].value='Yahoo'", element);
									})
								});
							});
                        	

Protractor Interview Questions

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech