Introduction to Selenium with JavaScript

What is Selenium, and how to use it for testing our Node.js web apps.

Posted by PeCoBe on 2022-10-17 ·

Selenium is a suite of tools for automating web browsers. In this guide we will focus in one tool in specific: Selenium WebDriver

I'm working in a special guide using Rust, Selenium WebDriver, Selenium Grid and Dockers, but is still in progress...

In this brief guide we will

  • Learn about Selenium Web
  • Installing Selenium
  • Finding elements
  • Interactions with elements
  • Assertions in Selenium

Selenium WebDriver is a automation API that drives a browser as a user would do.

img

Installing Selenium

We are using Node.js, so in order to kickstart our project, we also need to make sure we have node and npm available for us.

node -v # Verify node is installed
npm -v # Verify npm is installed
npm init # Initialize npm project
npm install selenium-webdriver chromedriver # install webdriver for your browser

Download the driver from WebDrivers for Chrome and add it to your PATH variable.

Create a new folder and inside a file called test.js

- test
    - test.js

The flow we will do is the following:

  1. Open a browser widnow
  2. Navigate to Google
  3. Input "pikachu" as a search term
  4. Press 'ENTER' to search
  5. Close the browser

We will increase the complexity of this same test case across the post.

// import chromedriver
require("chromedriver");

// import classes from selenium
const {Builder, By, Key, until} = require('selenium-webdriver');

// define a new async function that will contain our test steps
async function myFirstTest() {

    // open chrome browser
    let driver = await new Builder().forBrowser('chrome').build();

    // go to the site we want to test
    await driver.get('http://www.google.com');

}

myFirstTest(); // call our function

We can run our test from the terminal using

node test/test.js

We can se how a new chrome windows is open, and navigate to our target site. Let's find now elements to interact with.

Finding elements

In order to interact with the browser, our script needs to be able to locate the elements we want to test.

We identify elements using their HTML properties or the DOM. There are many ways to find and locate HTML elements. We will not use all of them.

We can use the following pages to practice our skills using selectors: The Internet

We want to locate the Search box in the page. Using the dev tools (right click > Inspect) we can see that we can identify the elemen by its name "q".

We will use the method findElement and the By.name class object.

Interacting with elements

Selenium has many methods for handling keyboard and mouse events, like click and type, as well as Actions classes, to provide more complex interactions like drag and drop.

In general, a step in Selenium follows the next structure:

driver.findElement(By.locator()).anAction;
action.moveToElement(element).complexAction.perform();

In our example we will add the following lines after driver.get to type our query and press enter.

    // get search box element with name = q
    driver.findElement(By.name('q')).sendKeys('pikachu', Key.ENTER);

Add the end, we will encompase our code in a try block, and add the an important step: close the browser.

...
    } finally {

        // close the web browser
        await driver.quit();
    }
...

Assertions in Selenium

Assertions are used to confirm if a statement is true or false, in this case if our validation passed or failed. For this guide, we will user Node.js's assert module, that includes:

  • assert()
  • deepEqual()
  • deepStrictEqual()
  • equal()
  • fail()
  • ifError()
  • notDeepEqual()
  • notDeepStrictEqual()
  • notEqual()
  • notStrictEqual()
  • ok()
  • strictEqual()

We are going to identify that the heading reads Pikachu to pass our test.

let heading = await driver.findElement(By.xpath('//*/h2/span')).getText();

We can run our test in the terminal using

node test/test.js
DevTools listening on ws://127.0.0.1:49713/devtools/browser/2995b096-4ebe-42e5-beac-db6a6eafdfd3
TEST PASSED

In the case the test failed, we can see a message similar to the following:

AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected

+ 'Pikachu'
- 'Pikacdhu'
        ^
    at myFirstTest (D:\Documents\Git\selenium-js\test\test.js:28:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: 'Pikachu',
  expected: 'Pikacdhu',
  operator: 'strictEqual'

If we pay attention, we can identify where and what was the cause of the error in the actual and expected values.

And that concludes our brief introduction to Selenium.

  • Learn about Selenium Web
  • Installing Selenium
  • Finding elements
  • Interactions with elements
  • Assertions in Selenium