Installing Selenium WebDriver using NPM simplifies JavaScript test automation by managing dependencies efficiently. With just a few commands, you can set up WebDriver, integrate it into your project, and start automating browser interactions.
Overview
Why Install and Use Selenium WebDriver with NPM?
- Easy Installation – Quickly set up Selenium WebDriver with a single command.
- Seamless Dependency Management – NPM handles package updates and compatibility.
- Fast Integration – Works with frameworks like Mocha, Jest, and Cucumber.
- Cross Browser Testing – Automate tests across Chrome, Firefox, and more.
- Scalability – Easily manage and execute large test suites efficiently.
This guide walks you through the installation process to get Selenium WebDriver running with NPM seamlessly.
What is Selenium WebDriver?
Selenium WebDriver is an open-source tool for automating browser interactions. You can write your scripts in languages like JavaScript to control browser actions such as clicking, typing, and navigating. WebDriver works directly with the browser, hence offering faster and more reliable automation than the previous Selenium tools.
Selenium is one of the top contenders for JavaScript automation testing because it integrates very well with JavaScript frameworks. It is used for task automation, regression testing and ensures that the web application under test works well on different browsers. Selenium also supports cross browser compatibility and, hence, has become a versatile tool for any form of web automation needs.
What is NPM?
NPM (Node Package Manager) is the default package manager for Node.js, used to install, manage, and share JavaScript libraries and dependencies. It simplifies the development process by allowing developers to easily integrate external packages into their projects.
Key Features of NPM
Here are the key features of NPM:
- Package Management: Install, update, and remove JavaScript libraries effortlessly.
- Dependency Handling: Automates dependency management for smooth project setup.
- Version Control: Ensures compatibility by managing different package versions.
- Global & Local Installation: Supports installing packages for specific projects or system-wide use.
- Scripts & Automation: Allows running custom scripts for tasks like testing, building, and deployment.
Read More: Architecture of Selenium WebDriver
Pre-requisites for Selenium WebDriver Installation
Before you get started with automation using Selenium WebDriver and JavaScript, some setup is needed. These setup requirements ensure that everything runs smoothly, so you’re good to go and ready to automate browser interactions.
1. Node.js and NPM: Selenium WebDriver for JavaScript is built on Node.js and NPM (Node Package Manager). Node.js is the runtime environment in which you run JavaScript outside a browser.
NPM is a library manager, for example, and Selenium’s dependent libraries and libraries. So install both.
NPM isn’t just for managing Selenium—it handles all project dependencies, ensuring seamless package installation, version control, and efficient project management.
2. JavaScript Knowledge: Selenium WebDriver sends messages to and receives responses from web pages with the help of JavaScript.
It can be helpful if you know how to write simple scripts, handle asynchronous code, and interact with web elements using JavaScript.
3. Web Browser: Selenium supports all major browsers, such as Chrome, Firefox, Safari, and Edge. You must install and update the browser you would like to automate.
4. WebDriver: You will need the WebDriver appropriate to the type of browser you are automating.
You will need the ChromeDriver for Chrome and the GeckoDriver for Firefox. These drivers act as a middleman between Selenium and the browser so the WebDriver can control the browser.
5. Text Editor/IDE: Choose a text editor or an Integrated Development Environment (IDE) like Sublime Text, Visual Studio Code, or Atom to write your JavaScript code.
Read More: Performing NodeJS Unit testing using Jest
Steps to Install Selenium WebDriver with NPM
Installing Selenium WebDriver with NPM for JavaScript automation is a straightforward process. Follow the steps below to set up your environment and start using Selenium in your projects.
Step 1: Install Node.js and NPM
If you haven’t already, download and install Node.js. The installation of Node.js automatically includes NPM, which you’ll use to manage your dependencies. You can verify that Node.js and NPM are installed correctly by running the following commands in your terminal:
node -v npm -v
These commands should return the version numbers of Node.js and NPM installed on your system.
Step 2: Create a New Project Folder
Create a new directory for your Selenium automation project. Open your terminal or command prompt and run the following command to create a new folder:
mkdir selenium-automation cd selenium-automation
This will create a new folder named selenium-automation and navigate you into it.
Step 3: Initialize a New Node.js Project
In your project folder, initialize a new Node.js project by running:
npm init -y
This will create a package.json file, which will store the details of your project and its dependencies.
Step 4: Install Selenium WebDriver
Now that your project is set up, it’s time to install Selenium WebDriver. Run the following command to install the Selenium package:
npm install selenium-webdriver --save
This will download and install the Selenium WebDriver package into your project’s node_modules folder and add it as a dependency in your package.json file.
Step 5: Install Browser Driver
Depending on the browser you want to automate, you’ll need to install the respective WebDriver. For example, if you’re using Chrome, you need to download ChromeDriver.
After downloading the driver, ensure it’s accessible by adding the location to your system’s PATH or specify its path directly in your Selenium script.
Step 6: Verify the Installation
To ensure that everything is set up correctly, create a simple JavaScript file, for example, test.js, in your project folder. Add the following code to open a browser using Selenium:
const {Builder} = require('selenium-webdriver'); const driver = new Builder().forBrowser('chrome').build(); driver.get('http://www.google.com') .then(() => driver.quit());
Save the file and run it in the terminal with:
node test.js
If everything is set up correctly, this script will open Chrome, navigate to Google’s homepage, and then close the browser.
Setting up and Running the Selenium Script
Once you’ve installed Selenium WebDriver and set up your project, you can start writing and running Selenium automation scripts. Here’s how to set up and execute your first Selenium script.
Step 1: Create a New JavaScript File
In your project folder, create a new JavaScript file, such as automation.js. This file will contain the code that automates the browser interaction.
Step 2: Import the Required Selenium Modules
To interact with Selenium WebDriver, you first need to import the necessary modules. At the top of your JavaScript file, add the following code:
const {Builder, By, Key, until} = require('selenium-webdriver');
- Builder: Helps create a new WebDriver instance.
- By: Allows you to locate web elements on the page (e.g., by ID, name, or class).
- Key: Used for simulating keyboard inputs.
- until: Helps you define conditions that the script should wait for (e.g., until an element is visible).
Step 3: Set Up the WebDriver
Next, you need to create a new instance of the WebDriver to control the browser. In this example, use Chrome, but you can use other browsers by modifying the browser parameter. Here’s how you set up the WebDriver for Chrome:
let driver = new Builder().forBrowser('chrome').build();
Step 4: Navigate to a Website
After setting up the WebDriver, the next step is to navigate to a website.
driver.get('http://www.google.com');
This command will open Google in the browser you specified (Chrome in this case).
Step 5: Interact with Web Elements
Selenium WebDriver allows you to interact with various elements on a web page. You can find elements by their ID, name, class, and more. Let’s say you want to search for a term on Google. You can locate the search box by its name (q) and type in a query:
driver.findElement(By.name('q')).sendKeys('Selenium WebDriver');
This line finds the search box on Google and types the search term “Selenium WebDriver” into it.
Read More: Selenium WebElement Commands
Step 6: Submit the Search
To submit the search query, you can simulate pressing the ‘Enter‘ key using Selenium’s Key module. Here’s how you do that:
driver.findElement(By.name('q')).sendKeys(Key.RETURN);
Step 7: Wait for an Element to Appear (Optional)
Selenium allows you to wait for elements to become available before performing actions. For example, if you want to wait for the Google results to load, you can use until to wait for a specific condition. Here’s how to wait until the search results appear:
driver.wait(until.elementLocated(By.id('search')), 10000);
This waits for the element with the ID search (the results container) to appear, with a timeout of 10 seconds.
Step 8: Close the Browser
Once the automation tasks are completed, you should close the browser to free up resources. You can do this by calling the quit() method on the driver:
driver.quit();
Step 9: Run the Script
Now that you’ve set up your script, you can run it. Open your terminal and navigate to your project folder. Run the script with the following command:
node automation.js
If everything is set up correctly, the script will open Google in Chrome, type “Selenium WebDriver” in the search box, submit the search, wait for the results, and then close the browser.
Why should you install and use Selenium WebDriver with NPM?
Using Selenium WebDriver with NPM streamlines the automation process by simplifying installation, dependency management, and integration with JavaScript frameworks. Here’s why it’s beneficial:
- Easy Installation: Setting up Selenium WebDriver with NPM is quick and straightforward. With a single command, you can install WebDriver and its dependencies without manual downloads or configurations.
- Seamless Dependency Management: NPM automatically handles package dependencies, ensuring that all required modules are installed and updated without compatibility issues.
This simplifies maintenance and management of test automation projects. - Fast Integration with Test Frameworks: Selenium WebDriver works seamlessly with popular JavaScript testing frameworks like Mocha,Jest, andCucumber, allowing developers to write and execute automated tests efficiently.
- Cross Browser Testing: Using Selenium WebDriver with NPM enables automation across multiple browsers such as Chrome, Firefox, Edge, and Safari, ensuring consistent web application performance across different environments.
- Scalability and Efficiency: With NPM, you can easily manage large test suites, integrate WebDriver into CI/CD pipelines, and execute parallel tests, making automation testing more scalable and efficient.
Why run Selenium WebDriver Tests on Real Devices & Browsers?
While emulators and Virtual Machines offer convenience, testing on real devices ensures accurate, real-world performance. Here’s why it matters:
- Accurate User Experience: Real devices capture network fluctuations, device quirks, and hardware variations that emulators miss.
- Cross Browser Testing: Different browsers render code uniquely. Testing on real browsers ensures a uniform experience across Chrome, Firefox, Safari, and more.
- Device-Specific Testing: Real devices support touch gestures, screen orientation changes, and hardware-specific interactions crucial for mobile testing.
- Performance & Speed Validation: Emulators often lag; real devices provide true speed and responsiveness insights.
- Network Variability: Simulate real-world conditions like slow connections or unstable mobile data to test app behavior.
- Comprehensive Test Coverage: Access a wide range of devices and browsers to ensure broad compatibility.
- Better Debugging: Identify device-specific bugs, rendering issues, and performance bottlenecks more effectively.
- Quality Assurance & User Confidence: Testing on real devices minimizes post-release issues, ensuring a polished, reliable application.
Your application can work appropriately across environments and have peak performance, offering optimum user experience when executing Selenium tests on actual devices and browsers.
With BrowserStackAutomate, you can test on 3,500+ real devices and browsers without setup hassles. Run Selenium WebDriver tests on real mobile and desktop environments to ensure your application delivers a seamless experience across different platform. It helps you integrate with CI/CD pipeline, enable parallel testing, debug faster and release with confidence.
Conclusion
Installing Selenium WebDriver with NPM is a straightforward process that enables seamless JavaScript-based test automation. By setting up WebDriver, managing dependencies with NPM, and leveraging WebDriver’s capabilities, you can efficiently automate browser interactions across different environments. Whether for local testing or running tests on cloud platforms like BrowserStack Automate, integrating Selenium with NPM streamlines your automation workflow. With this setup, you can write, execute, and scale reliable test scripts, ensuring robust web application quality.
BrowserStack Automate makes testing easy on many real devices and browsers without setting up a physical device lab. It enhances test coverage and improves debugging to deliver high-quality web applications that work well in most environments.