webdriverjs dropdown

WebDriverJS Dropdown

Reading Time 1 minute

Do you know how to use WebDriverJS to interact with a Dropdown field? Let’s use WebDriverJS dropdown to select a value?

It is important to be able to select a value from a dropdown box. Let’s have a look at how we can use WebDriverJS to select an item from a dropdown box.

WebDriverJS Dropdown

In the code snippet below, we navigate to a test page which contains a dropdown box. Examine the code below:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.get('http://www.thetestroom.com/webapp');
driver.findElement(webdriver.By.id('adoption_link')).click();

The code above navigates to www.TheTestRoom.com, goes to the test site (webapp) and then clicks on the ‘Adoption’ link. Now let’s try to see how we can interact with the dropdown box on that page.

Select from Dropdown field

The code below introduces a selectFromDropdown function.

SelectFromDropdown Function
In order to select a value from the dropdown field, we will introduce a new function.

function selectFromDropdown(value){const valueSelected = webdriver.By.css('[id="start_select"]' + ' option[value="' + value + '"]');
    driver.findElement(webdriver.By.css('[id="start_select"]')).click();
    driver.findElement(valueSelected).click();
}

In the ‘selectFromDropdown’ function, we firstly identify the id of the dropdown field as well as capturing a possible value from the dropdown. We then assign this to a constant variable called ‘valueSelected’.

Finally we click on the dropdown field itself which displays all the options. This then allows us to see all possible options which we are then able to click on.

Let’s have a look at how the script now looks:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
 
driver.get('http://www.thetestroom.com/webapp');
driver.findElement(webdriver.By.id('adoption_link')).click();
selectFromDropdown('today');
driver.quit();
 
function selectFromDropdown(value){const valueSelected = webdriver.By.css('[id="start_select"]' + ' option[value="' + value + '"]');
    driver.findElement(webdriver.By.css('[id="start_select"]')).click();
    driver.findElement(valueSelected).click();
}

Using the function above, you should now be able to change it to help select a value from a dropdown box.

Mo

I am a passionate tester, father, husband and gamer. I love to write blogs about Software Testing and generally contribute back to the Software Testing world.

More Posts - Twitter - Facebook

Published by

Mo

I am a passionate tester, father, husband and gamer. I love to write blogs about Software Testing and generally contribute back to the Software Testing world.