Learn

Selenium and JavaScript: Getting started

Automated testing is an important part of modern software development. It helps teams catch bugs and ensure their applications work as expected. One of the most important tools for automated testing is Selenium; when combined with JavaScript, it becomes even more versatile.

Author:

Guest Contributors

Date: Jan. 18, 2024

In this post, we’ll explore what Selenium is, how you can use it with JavaScript, the benefits of combining the two, and how you can get started with Selenium and JavaScript for automated testing.

Selenium provides support for various programming languages, including JavaScript, Python, and Java, making it a great choice for automated testing.

What is Selenium?

Selenium is an open-source framework for automating web applications for testing. It provides a way to automate interactions with a webpage, including clicking different buttons, filling out long and short forms, and navigating through web applications. Selenium provides support for various programming languages, including JavaScript, Python, and Java, making it a great choice for automated testing.

The framework consists of a number of components, including the Selenium WebDriver, the Selenium IDE, and the Selenium Grid. The WebDriver, in particular, is the most commonly used component because it allows you to write automated tests that interact with webpages in a programmatic way. It’s a very powerful tool that enables running test scripts on applications on various operating systems and browsers. Selenium reduces the need for manual testing, which ultimately helps speed up the development process.

Can I use Selenium with JavaScript?

Selenium WebDriver provides JavaScript binding that allows you to write automation scripts in JavaScript. This is quite useful if your web application relies heavily on JavaScript for interactivity and functionality, since it allows you to test your application more comprehensively. The combination of JavaScript and Selenium is particularly effective for testing web apps made with JavaScript frameworks like Vue.js, React, and Angular.

Benefits of using JavaScript with Selenium

Using JavaScript with Selenium for web automation makes sense because it’s already used extensively for web development. Plus, most developers are familiar with JavaScript and it’s pretty easy to write automation tests.

When combined, the two can automate various web testing tasks like navigating through pages, clicking on links and buttons, filling out forms, etc. They’re also cross-platform and cross-browser compatible, making them suitable for testing web apps on different operating systems and across multiple browsers. The versatility of JavaScript also makes it easy to handle browser-specific behavior, ensuring consistent performance.

It’s easy to use JavaScript and Selenium to test mobile applications, integrate with other tools, and generate reports. You can also seamlessly integrate JavaScript with popular testing libraries and frameworks, making it easier to set up a testing environment and run your tests.

How do I get started with Selenium with JavaScript for automated testing?

Whether it’s platforms like Linux or Windows or browsers like Safari, Chrome, or Firefox, Selenium allows cross-browser, platform-independent testing, and it’s quite easy to get started.

Prerequisites

To be able to use JavaScript with Selenium, you first need to install Node.js (and the node package manager). You can download it from the official website based on your operating system.

To see whether both were installed, run the following:

node -v
npm -v

Once you confirm that both node and npm are installed, install the IDE of your choice. I prefer using VSCode, but you can choose whatever you prefer.

Next, initialize a new project by running

npm init

And then install the Selenium WebDriver by running the following:

npm install selenium-webdriver

Understanding how Selenium works

Before we write our first automation test script, it’s important to understand how the Selenium WebDriver works. WebDriver is basically a protocol and API that allows you to define a language-neutral interface to control the web browser’s behavior.

Each browser has a certain WebDriver implementation that’s simply referred to as a driver. This is what delegates tasks to the browser and is responsible for communication between the browser and Selenium. The WebDriver allows you to automate browser testing by simulating actions like clicking buttons or entering text in inputs on a website. In fact, the WebDriver for JavaScript allows you to use promises, which helps ensure that all the steps of your tests are executed in sequence.

To start, you need to specify the browser you want to use for your test as well as the website you want to test. Then, to make sure that Selenium is able to interact with elements present on the website, you need to explicitly tell it what it should look for. This is possible with the findElement() method. It helps Selenium find elements on a page using DOM element selectors such as CSS selectors or ID. Once Selenium finds the element to interact with, it executes all the specified actions, seamlessly automating the web testing process. You can add logs within your code to keep track of your app’s progress.

Basic examples

Now that you know how Selenium works, let’s write a few basic tests to help you get started.

Example #1: Searching for something on Google

Let’s start with the most basic web interaction: searching for something on Google.

To do so, first import the Selenium WebDriver components. We’ll use these to set up and perform automated browser interactions.

const { Builder, By, Key, until } = require(“selenium-webdriver”);

Then, initialize a WebDriver instance for Google Chrome (or the browser of your choice) by running the following:

const driver = new Builder().forBrowser(“chrome”).build();

We’re using the Builder class to configure and build the WebDriver instance. We’ve set the target to “chrome.”

Next, we need to define an asynchronous function that encapsulates our test script.

(async function example() {

try {

await driver.get(“https://www.google.com”);

await driver.findElement(By.name(“q”)).sendKeys(“Selenium”, Key.RETURN);

await driver.wait(until.titleIs(“Selenium – Google Search”), 1000);

} finally {

await driver.quit();

}

})();

In the “try” block, we’ve defined the following test actions:

  1. The driver navigates to Google’s homepage.
  2. It then finds the input element with the name “q.” This corresponds to Google’s search bar.
  3. It sends the text “Selenium” to the search bar, since this is what we want to search for.
  4. We define Key.RETURN to simulate pressing the “Enter” key to submit our search query.
  5. Then, the program waits for 1,000 milliseconds (one second) to ensure the search result page loads fully before terminating the WebDriver instance and finishing the test.

To run this code, simply save the file and run it. The WebDriver will launch your browser automatically and perform the steps mentioned above. Once it successfully does its work, it’s going to close the browser window, and you won’t see any error in the console.

Example #2: Searching for something on Amazon

In this example, we’ll automate a search on Amazon. The following code essentially opens Amazon’s homepage, locates the search input field by ID, enters the word “Laptop,” and waits for the search results page to load.

const { Builder, By, Key, until } = require(“selenium-webdriver”);

const driver = new Builder().forBrowser(“chrome”).build();

(async function amazonSearchExample() {

try {

await driver.get(“https://www.amazon.com”);

const searchBox = await driver.findElement(By.id(“twotabsearchtextbox”));

await searchBox.sendKeys(“Laptop”, Key.RETURN);

await driver.wait(until.titleContains(“Laptop”), 5000);

} finally {

await driver.quit();

}

})();

Example #3: Testing the log-in functionality of an example site

For this example, we’ll automate the process of logging in to an example website. The website I’m using for this purpose is the write a few basic tests. For this code to work, we need to provide a valid username and password. If you provide the wrong credentials, the automation is going to fail, and you’re going to see an error in the console.

const { Builder, By, until } = require(“selenium-webdriver”);

const assert = require(“assert”);

async function loginTest() {

let driver = await new Builder().forBrowser(“chrome”).build();

try {

await driver.get(“https://test-login-app.vercel.app/”);

await driver.findElement(By.id(“email”)).sendKeys(“test@gmail.com“);

await driver.findElement(By.id(“password”)).sendKeys(“Password@12345”);

await driver.findElement(By.name(“login”)).click();

const pageTitle = await driver.getTitle();

await driver.wait(until.titleIs(“Welcomepage”), 4000);

} finally {

await driver.quit();

}

}

loginTest();

When combined, JavaScript and Selenium are powerful tools for the automated testing of web applications

Conclusion

When combined, JavaScript and Selenium are powerful tools for the automated testing of web applications. The versatility and cross-browser and cross-platform compatibility of the two make using both an excellent choice for new and experienced testers.

In this post, we’ve covered basic tests, but you can also integrate a testing framework or library like Mocha or Jest to structure your tests. By incorporating Selenium and JavaScript into your development toolkit, you’ll be able to create robust test scripts that ensure the reliability and quality of your web apps.

This post was written by Nimra Ahmed. Nimra is a software engineering graduate with a strong interest in Node.js & machine learning. When she’s not working, you’ll find her playing around with no-code tools, swimming, or exploring something new.

Author:

Guest Contributors

Date: Jan. 18, 2024