DEV Community

Roel
Roel

Posted on

How to JS: Automate testing with Selenium

How to Automate Browser Testing with Selenium in JavaScript

Automated browser testing is a must for any web developer to ensure their applications function correctly. In this post, we'll walk through setting up Selenium with JavaScript to automate a simple browser task: opening a webpage and clicking a button.

Prerequisites

To follow along, you’ll need:

  • Node.js and npm installed.
  • Google Chrome and ChromeDriver installed (or another browser and its respective driver).

Step 1: Set Up Your Project

First, create a new folder for your project. Open your terminal and run:

mkdir selenium-test
cd selenium-test
Enter fullscreen mode Exit fullscreen mode

Next, initialize a new Node.js project:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This command generates a package.json file that keeps track of your project’s dependencies.

Step 2: Install Selenium WebDriver

We’ll use npm to install Selenium WebDriver and ChromeDriver:

npm install selenium-webdriver chromedriver --save
Enter fullscreen mode Exit fullscreen mode

These packages provide the necessary libraries and tools to automate Chrome with Selenium.

Step 3: Write Your Selenium Script

Create a new file named test.js in your project folder. This script will open a webpage, wait for a button to become clickable, and then click it.

const { Builder, By, until } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

// Helper function to pause the script
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function runTest() {
  // Configure Chrome to suppress unwanted prompts
  let options = new chrome.Options();
  options.addArguments('--no-default-browser-check', '--no-first-run', '--disable-default-apps', '--disable-infobars');

  let driver = await new Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();

  try {
    // Open the target webpage
    await driver.get('https://example.com'); // Change this URL to the site you want to test

    // Wait for an element to load
    await driver.wait(until.elementLocated(By.className('sample-class')), 10000);
    console.log('Found element with class "sample-class".');

    // Generic wait for 6 seconds to handle any dynamic content
    await sleep(6000);

    // Wait for the button to be clickable
    await driver.wait(until.elementLocated(By.id('sample-button')), 10000);

    // Re-locate the button to ensure it’s still in the DOM
    let button = await driver.findElement(By.id('sample-button'));
    console.log('Button located:', button);

    // Click the button
    await button.click();
    console.log('Button clicked successfully.');

    // Wait for the next page or action to load
    await driver.wait(until.urlContains('new-page'), 10000);
    console.log('Navigation to new page was successful.');

  } catch (error) {
    console.error('Error during the test:', error);
  } finally {
    // Always close the browser
    await driver.quit();
  }
}

runTest();
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Script

To execute your script, run:

node test.js
Enter fullscreen mode Exit fullscreen mode

Chrome will open and perform the actions defined in your script. Watch the console for logs indicating each step's progress.

Troubleshooting

  • StaleElementReferenceError: This happens when the DOM changes after finding an element. To avoid this, always re-locate elements right before interacting with them.
  • Timeouts: If an element takes longer to load, increase the timeout in driver.wait().

Conclusion

You now have a basic setup for automated browser testing using Selenium and JavaScript. This setup can be easily expanded to include more complex interactions, checks, and validation steps.

Remember to keep your drivers updated to match your browser versions and consider using a headless mode for CI/CD environments.

If you want to host it in Azure check out my other post: https://dev.to/iamrule/how-to-azure-host-a-selenium-javascript-node-application-in-azure-and-send-email-notifications-on-failures-2aio

Happy testing!

Top comments (0)