WebDriverJS Dropdown

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.

WebDriverJS Switching Windows

When writing an automated test, you may encounter scenarios where you might have to switch browser windows. In this post we will look at how we can switch windows.

WebDriverJS Switching Windows

Firstly, let’s write out in comments what we would like to achieve.

// Save location to parent window
// Print parent window title
// Switch to new window
// Print text in newly switched window
// Switch back to parent window
// Print parent window title

Assuming we are able to achieve the above scenario, we should be able to figure out how to switch windows.

Switching Windows

In order to switch windows, we need to use the ‘getAllWindowHandles()’ command. Let’s have a look below:

driver.getAllWindowHandles().then(function gotWindowHandles(allhandles) {
    // Save location to parent window
    // Print parent window title
    // Switch to new window
    // Print text in newly switched window
    // Switch back to parent window
    // Print parent window title
});

Since ‘getAllWindowHandles()’ returns a promise, we need to wrap it in a ‘then’.

Further Switching Windows

Let’s take this a step further and try to address each of the comments:

driver.getAllWindowHandles().then(function gotWindowHandles(allhandles) {
    // Save location to parent window
    var parent = driver.getWindowHandle();
 
    // Print parent window title
    driver.getTitle().then(function (text) {
        console.log('Parrent Windows: ' + text);
    });
 
    // Switch to new window
    driver.switchTo().window(allhandles[allhandles.length - 1]);
 
    // Print text in newly switched window
    driver.findElement(webdriver.By.css('h1')).then(function (heading) {
        heading.getText().then(function (text) {
            console.log('Child Windows: ' + text);
        });
    });
 
    // Switch back to parent window
    driver.switchTo().window(parent);
 
    // Print parent window title
    driver.getTitle().then(function (text) {
        console.log('Parrent Windows: ' + text);
    });
});

The main things to note here are the variable to capture the parent window and how we switch back and forth between the parent and child windows. It is also important to note that when switching windows, the driver simple gains control over eachwindow. We do not need to use a different driver instance.

Full Example

Script.js

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('footer_term')).click();
 
driver.getAllWindowHandles().then(function gotWindowHandles(allhandles) {
    // Save location to parent window
    var parent = driver.getWindowHandle();
 
    // Print parent window title
    driver.getTitle().then(function (text) {
        console.log('Parrent Windows: ' + text);
    });
 
    // Switch to new window
    driver.switchTo().window(allhandles[allhandles.length - 1]);
 
    // Print text in newly switched window
    driver.findElement(webdriver.By.css('h1')).then(function (heading) {
        heading.getText().then(function (text) {
            console.log('Child Windows: ' + text);
        });
    });
 
    // Switch back to parent window
    driver.switchTo().window(parent);
 
    // Print parent window title
    driver.getTitle().then(function (text) {
        console.log('Parrent Windows: ' + text);
    });
});

The should output the following:

Expected Output

Parrent Windows: Zoo Adoption | Home
Child Windows: Terms of the site
Parrent Windows: Zoo Adoption | Home

WebDriverJS Properties File

The concept of Properties is a great way to control test configuration. WebDriverJs Properties can help to scale automated tests.

When writing scripts using WebDriverJS, it is important to consider the scale of the test. Being able to change the parameters of multiple tests with a single change can helps scale tests.

WebDriverJS Properties without Properties

Let’s take a simple script. See below:

script.js

var webdriver = require('selenium-webdriver’);
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.get('http://www.thetestroom.com');

The script above is very simple. It opens a Chrome browser and navigates to www.TheTestRoom.com. Assume for a moment that the URL for TheTestRoom changes to something else. If the URL changed, we would have to update the script. Updating a single script is not a problem, in fact it is very straight forward. However, what if we have 1000’s of scripts, all which used the URL. With our current approach we would have to update each script individually.

Introducing Properties

Now let’s take a look at the same file, this time however the URL is coming from a properties file.

script.js

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
var prop = require('./proptest');
driver.get(prop.TTL);

properties.js

module.exports = {
    TTL: 'http://www.thetestroom.com'
};

The same URL is now being set in a properties file. The properties file is exported via module.exports. This allows us to use the concept of creating variables in one file and consuming it in many other places.

If the URL changes, we only need to update the properties file ie. in one place. With this approach, we do not need to care about how many files are using the URL. This is because a single change would effect all files automatically.

Conclusion

To wrap this up, what advantage does this actually bring?

Well:
* A single change will effect all files
* Test files becomes easier to manage
* There should not be an instance of ‘accidentally forgetting to update a URL’
* Increase variable names readability

You can apply the same mechanics to help configure what environments to run against, when to run, test priority changes, test suites etc.

Installing WebDriverJS

Welcome to an easy and simple guide to installing WebDriverJS. WebDriverJS is a Web Automation framework which we can use to emulate user actions in a web browser such as Chrome or Firefox. It is a great tool when used in conjunction with NodeJS. In this tutorial we will firstly ensure we have all the required tools in place to eventually write a basic script which will open a Chrome browser and navigate to www.thetestroom.com, let’s begin.

Installing WebDriverJS – Installing NodeJS

There are a number of ways to install WebDriverJS but perhaps the most efficient and simplest way is to do it through ‘npm’. ‘npm’ is NodeJS’s package manager and it really helps to download modules and dependency through the command line very easily. We will see how to use ‘npm’ soon(ish), firstly we need to install NodeJS.

Navigate to NodeJS.org and download the LTS version. This is assumed to be the most stable version and should be very comfortable to use. Once downloaded simply run the installer.

Now that you have installed NodeJS on your machine lets check if the installation succeeded. Open a console window and type in the following:

node -v

This should return the version of NodeJS which you downloaded. With this done now let’s check to see that you have ‘npm’ installed. Type the following in the console window:

npm -v

This should return the version of ‘npm’ you have. Great, we now have both NodeJS and ‘npm’ installed.

Project Setup

With NodeJS now ready, let’s go ahead and start setting up our project directory. Navigate to a directory of your choice and create a new folder called ‘webdriver-js-project’. Before we actually begin to use ‘npm’ to install WebDriverJS we should spend a second or two deciding on which web browser to run our WebDriverJS scripts against? There are a number of options but for the moment (and to keep things a little simple) I would suggest we roll with ChromeDriver. ChromeDriver is an executable file which is used to control Chrome. This means you will need to have Chrome installed on your machine. Ensure that you have Google Chrome installed and once confirmed navigate to ChromeDriver and download the latest ChromeDriver. Once Downloaded simply extract the driver and place the exe file in the ‘webdriver-js-project’ folder.

Great stuff, you now have both Google Chrome as well as the driver ready on your machine. The final step of the setup phase is to download WebDriverJS via ‘npm’. Open a command windows (or terminal) and ensure you are in ‘webdriver-js-project’ and run the following command:

npm install --save--dev selenium-webdriver

This will install WebDriverJS locally in ‘webdriver-js-project’. If you have a quick look now at your project then you will notice that now there is a new directory called ‘node_modules’. If you dig into that folder then you will also notice that it contains a ‘selenium’ folder. Congratulations, we just used ‘npm’ to install WebDriverJS.

We now have all the required components to start writing our first script in WebDriverJS.

Writing A Basic WebDriverJS Script

Finally, let’s write our script. Let’s begin by creating a JavaScript file. Navigate to ‘webdriver-js-project’ and create a new file called test.js. With the test file now created add this line of code:

var webdriver = require('selenium-webdriver');

Let’s discuss what is happening in the line above. The line above is declaring a new variable called webdriver. We then assigned selenium-webdriver (the same module which we installed via ‘npm’) to that variable we gained access to the building methods inside Selenium. With this said let’s create our driver variable:

var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();

As you can see we are now able to use our webdriver variable to identify the browser we want to use and build it as part of a driver instance. Once we build the instance we are able to assign this to a driver variable. The driver variable now contains all the methods which can now allow us to interact with the chrome browser. With this said lets actually do something with the browser, let’s try to navigate to a URL:

driver.get('http://www.thetestroom.com');

The line above uses the driver variable that we created and makes a call to the ‘get’ method. This method is used to navigate to a URL. Your test.js file should now look like this:

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

With the script now ready let’s actually run the file. Using command line navigate to ‘webdriver-js/project’ directory and run the following command:

node test.js

This should have now opened a Chrome browser and navigated to www.thetestroom.com. Congratulations as you have just written your test script using WebDriverJS.