keepcalculator

06 Numbers and Powers

Selenium Automation Tests with Node.js: Step-by-Step

Card No. 06·52052 · Updated · Standard formula, shown below

This guide walks you through setting up and running Selenium automation tests using Node.js, from installing the necessary packages to writing and executing your first test script. You’ll learn how to control a real browser programmatically, which is useful for end-to-end testing of web applications, automating repetitive tasks, and verifying UI behavior. By the end, you’ll have a working test that opens a website, interacts with elements, and checks expected outcomes.

What You’ll Need

  • Node.js (version 14 or later) installed on your machine. You can download it from the official Node.js website.
  • A code editor (like Visual Studio Code, Sublime Text, or any other).
  • A web browser installed (Chrome, Firefox, or Edge). This guide uses Chrome as an example.
  • Basic familiarity with JavaScript and command-line tools.

Step-by-Step

  1. Set up a new project directory – Open your terminal and run mkdir selenium-node-test then cd selenium-node-test. This creates a clean folder for your project.
  2. Initialize the project – Run npm init -y to create a package.json file with default settings. This file tracks your dependencies and scripts.
  3. Install Selenium WebDriver – Run npm install selenium-webdriver. This installs the official Selenium JavaScript bindings. If you plan to use Chrome, also install the ChromeDriver manager: npm install chromedriver. For Firefox, use geckodriver instead.
  4. Create a test file – Create a new file named test.js in your project folder. This will contain your automation script.
  5. Write the basic test script – Open test.js and add the following code:
    const { Builder, By, until } = require('selenium-webdriver');
    const chrome = require('selenium-webdriver/chrome');
    
    (async function example() {
      let driver = await new Builder().forBrowser('chrome').build();
      try {
        await driver.get('https://www.google.com');
        let title = await driver.getTitle();
        console.log('Page title:', title);
        await driver.quit();
      } catch (error) {
        console.error('Test failed:', error);
        await driver.quit();
      }
    })();
        

    This script opens Chrome, navigates to Google, and prints the page title.

  6. Run the test – In your terminal, execute node test.js. You should see Chrome open and then close, and the terminal will display the page title. If you see an error about ChromeDriver, ensure you installed it correctly and that it matches your Chrome version.
  7. Add an actual assertion – To make this a real test, modify the script to check that the title is as expected. Use Node’s built-in assert module:
    const assert = require('assert');
    // ... after getting title
    assert.strictEqual(title, 'Google');
    console.log('Test passed!');
        

    This will throw an error if the title doesn’t match, failing the test.

  8. Interact with elements – To test more than just page loads, you can find elements and interact with them. For example, to search on Google:
    let searchBox = await driver.findElement(By.name('q'));
    await searchBox.sendKeys('Selenium Node.js');
    await searchBox.submit();
    await driver.wait(until.titleContains('Selenium Node.js'), 10000);
    console.log('Search completed');
        

    This types into the search box and waits for the results page to load.

  9. Organize with a test framework – For multiple tests, use a framework like Mocha or Jest. Install Mocha with npm install mocha, then modify your script to use describe and it blocks. Update package.json to set "test": "mocha" and run npm test.
  10. Run tests in headless mode – For CI/CD environments, you may want to run without a visible browser. Add --headless to the Chrome options:
    let driver = new Builder().forBrowser('chrome')
      .setChromeOptions(new chrome.Options().headless())
      .build();
        

    This runs the same tests without opening a window.

Common Mistakes

  • Forgetting to install the driver – Selenium needs a driver to communicate with the browser. If you get a “cannot find ChromeDriver” error, install the driver package or set the path manually.
  • Using the wrong locator – Elements may not be found if the selector is incorrect or the page hasn’t loaded yet. Always use wait or until to ensure the element is present.
  • Not closing the driver – Leaving the browser open can cause memory leaks and lock resources. Always call driver.quit() in a finally block or after the test.
  • Hardcoding waits – Using driver.sleep(5000) makes tests slow and flaky. Prefer explicit waits with until.elementLocated or until.elementIsVisible.
  • Ignoring asynchronous nature – Selenium commands return promises. Forgetting await can cause tests to run out of order or fail silently.

Tips

  • Use CSS selectors or XPath – They are more robust than class names that change often. For example, By.css('button.submit') is more specific than By.className('btn').
  • Keep tests independent – Each test should not rely on state from a previous test. Use beforeEach to set up a clean state.
  • Use page object model – For larger projects, encapsulate selectors and actions in separate classes to improve maintainability.
  • Run tests in parallel – Use tools like Selenium Grid or test framework features to run tests concurrently and save time.
  • Log and screenshot on failure – Capture a screenshot when a test fails to help debug. Use driver.takeScreenshot() and save the base64 string to a file.

Troubleshooting

“SessionNotCreatedError: This version of ChromeDriver only supports Chrome version X” – This means your ChromeDriver and Chrome browser versions don’t match. Update both to the latest versions, or use the chromedriver npm package which automatically downloads the correct version for your installed Chrome.

“Unable to find element” – The element isn’t in the DOM yet or the selector is wrong. Use driver.wait(until.elementLocated(By.id('myId')), 10000) to wait for it. Double-check the selector by inspecting the page in your browser’s dev tools.

“WebDriverError: unknown error: cannot find Chrome binary” – Selenium can’t locate the Chrome executable. Ensure Chrome is installed in the default location, or specify the path using chrome.Options().setChromeBinaryPath('/path/to/chrome').

Test times out – Increase the timeout in your test framework. For Mocha, use this.timeout(30000) in the test or set it globally. Also check if your wait conditions are too short.

Port 9515 already in use – This occurs when multiple tests run simultaneously. Use a different port by setting driver = new Builder().usingServer('http://localhost:9515') or let Selenium pick a free port automatically.

Frequently Asked Questions

Q: Do I need to install a separate driver for each browser?

Yes. Chrome uses ChromeDriver, Firefox uses GeckoDriver, and Edge uses EdgeDriver. Install the respective npm package or manage them manually.

Q: Can I use Selenium with a cloud browser service?

Yes, you can connect to services like Sauce Labs or BrowserStack by providing the remote URL and credentials in the Builder. This allows testing on many browser/OS combinations without local setup.

Q: How do I handle pop-ups or alerts in Selenium?

Use driver.switchTo().alert() to interact with JavaScript alerts. You can accept, dismiss, or get the alert text. For browser-level pop-ups, use the appropriate driver methods.

Q: Is Selenium suitable for API testing?

No, Selenium is designed for browser automation. For API testing, use tools like Postman or libraries like Axios with a test runner.

Q: Can I run Selenium tests on a headless server?

Yes, use the headless mode of your browser (e.g., --headless for Chrome). This is common in CI environments where no display is available.

Q: How do I wait for a page to load completely?

Use driver.get() which waits for the page to load by default. For dynamic content, use explicit waits like until.elementLocated or until.elementIsVisible.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →