Articles

Getting Started with Selenium in JavaScript

2024-08-05·3 min read
Photo by Boitumelo on Unsplash

The rapid pace of web development brings along a host of challenges, one of which is ensuring that web applications behave as expected across different browsers and devices. Manual testing can be labor-intensive and prone to human error, which is why automated testing tools have gained massive popularity. Enter Selenium: a robust framework for automating web applications. This guide will walk you through how to get started with Selenium using JavaScript, helping you streamline your testing process.

Understanding Selenium

Selenium is an open-source framework widely used for automating web browsers. It supports multiple programming languages, including Java, C#, Python, and, of course, JavaScript. With Selenium, you can perform browser automation tasks, ranging from simple form submissions to complex workflows simulating user interactions.

Selenium consists of four main components:

  1. Selenium WebDriver: Facilitates browser automation.
  2. Selenium Grid: Allows parallel testing across various browsers and machines.
  3. Selenium IDE: A record-playback tool for creating test scripts without knowledge of programming.
  4. Selenium RC (Remote Control): An older tool, now largely replaced by WebDriver, used for browser automation.

For this guide, we will focus on Selenium WebDriver, the most widely used component, in combination with JavaScript.

Why Use JavaScript with Selenium?

JavaScript is the backbone of modern web development, so it makes sense to also use it for test automation. By using JavaScript with Selenium, you have the advantage of a cohesive technology stack. This can lead to more efficient troubleshooting and a more straightforward workflow since you’ll likely be familiar with both the language and relevant libraries for web development.

Setting Up Your Environment

Before diving into writing your first Selenium test, you'll need to set up your environment. Here’s a simple checklist to get you started:

  1. Install Node.js: Selenium WebDriver with JavaScript is best managed through Node.js. Download and install Node.js from the official website.
  2. Install npm (Node Package Manager): npm comes bundled with Node.js, and you'll use it to install Selenium WebDriver and other dependencies.
  3. Set Up a Project Directory: Create a directory for your test project and navigate into it using your terminal or command prompt.
mkdir selenium-js-demo
cd selenium-js-demo

Installing Selenium and WebDriver

To start using Selenium, you will need to install a few npm packages. The essential ones are selenium-webdriver and potentially the browser driver (e.g., chromedriver).

Run the following command:

npm init -y
npm install selenium-webdriver

For Chrome:

npm install chromedriver

For Firefox:

npm install geckodriver
Photo by Aaron Burden on Unsplash

Writing Your First Test Script

Once you've installed the necessary packages, you can write your first Selenium test script. Create a file named test.js in your project directory:

touch test.js

Open test.js in your preferred text editor and add the following code:

const { Builder, By, Key, until } = require("selenium-webdriver")
const chrome = require("selenium-webdriver/chrome")
;(async function example() {
    // Set up the Chrome driver
    let driver = await new Builder().forBrowser("chrome").build()

    try {
        // Navigate to Google
        await driver.get("http://www.google.com")

        // Find the search box, type in "Selenium JavaScript", and hit Enter
        await driver.findElement(By.name("q")).sendKeys("Selenium JavaScript", Key.RETURN)

        // Wait until the title is updated
        await driver.wait(until.titleIs("Selenium JavaScript - Google Search"), 1000)
    } finally {
        // Quit the driver
        await driver.quit()
    }
})()

This script does the following:

  1. Initializes a new WebDriver instance for Chrome.
  2. Navigates to Google's homepage.
  3. Finds the search input element by its name attribute, types "Selenium JavaScript" into the search box, and presses the Enter key.
  4. Waits until the page title changes to "Selenium JavaScript - Google Search".
  5. Closes the browser.

Run your script using Node.js:

node test.js

Handling Common Scenarios

Waiting for Elements

In web automation, elements sometimes take time to load. Selenium offers several mechanisms to handle these waits:

  1. Implicit Waits: Sets a default wait time for the entire session.
  2. Explicit Waits: Allows you to wait for a specific condition to be true.
await driver.wait(until.elementLocated(By.name("q")), 10000)

Interacting with Different Browsers

To interact with browsers other than Chrome, change the driver setup in your script:

let driver = await new Builder().forBrowser("firefox").build()

Remember to install the appropriate browser driver via npm.

Capturing Screenshots

Capturing screenshots can be valuable for debugging:

let screenshot = await driver.takeScreenshot()
require("fs").writeFileSync("screenshot.png", screenshot, "base64")

Best Practices

  1. Modularize Code: Break down your test scripts into reusable functions.
  2. Use Environment Variables: Keep sensitive data like login credentials out of your code.
  3. Handle Exceptions: Comprehensive error handling can save you a lot of headache.
  4. Incorporate CI/CD: Use tools like Jenkins or GitHub Actions for continuous integration and continuous deployment.

Wrapping Up

Getting started with Selenium in JavaScript doesn't have to be daunting. With the right setup and a little bit of code, you can quickly move from manual testing to robust, automated workflows. Selenium's compatibility with JavaScript makes this transition seamless, offering a well-rounded solution for modern web development challenges. By following this guide, you should be well on your way to mastering Selenium and enhancing your development process. Happy testing!

Report bugs like it's 2024
Bug reports has looked the same since forever. You try to jam as much detail as possible to avoid the dreaded "can't reproduce". It's time to fix that. Whitespace captures every possible detail automatically and puts it all in a neat little package you can share as link.

Read more

Getting Started with Playwright in JavaScript

Development and testing can often feel like taming a herd of wild animals. Read more

Published 4 min read
Getting Started with Playwright in Node.js

In the world of web development, automated browser testing can be a complex yet essential task. Read more

Published 3 min read
Getting started with Selenium in C#

In today's fast-paced development environment, ensuring that web applications are functioning correctly is crucial. Read more

Published 4 min read
Getting Started with Selenium in PHP

Imagine this: you've just finished building a shiny new PHP application that you’re incredibly proud of. Read more

Published 3 min read
Getting Started with Selenium in Python

Ever found yourself in a situation where you need to automate tedious web tasks but don't know where to start? Perhaps you're frequently logging into a website, scraping data for a project, or testing web applications manually. Read more

Published 3 min read
Getting Started with Selenium in Java

Developers are often on the hunt for efficient ways to automate web browser interactions for testing purposes. Read more

Published 4 min read
Selenium vs Puppeteer vs Playwright

Web automation has become an essential tool in the arsenal of modern developers. Read more

Published 3 min read
Getting Started with Selenium in Node.js

Web development projects often require automated testing to ensure consistent and reliable performance across various browsers. Read more

Published 3 min read
What is KPI?

Key Performance Indicators (KPIs) are measurable values that demonstrate how effectively an organization is achieving key business objectives. Read more

Published 2 min read
Bug report template

Copy this bug report template into your bug tracking tool and use it as a template for all new bugs. This templates gives you a great foundation to organize your bugs. Read more

Published 1 min read
One-click bug reports straight from your browser
Built and hosted in EU 🇪🇺