Users play a vital role in the success of any product, especially when it comes to user interface – we cannot compromise. We need to introduce functional automation testing to our product and make sure the product’s functionality is as expected and deliver a flawless experience to our end users. There are many tools to do so, Selenium being the most popular among them for web automation (Check out all the latest updates to Selenium 4). In this tutorial, we will focus on JavaScript with Selenium for web automation.
đ If you are looking for an all-in-one test automation framework for web & mobile that supports JavaScript â there is also an easy open source solution provided by TestProject. The free platform recently introduced its OpenSDK which opens a whole new chapter for supporting developers as well as testers in their work. By using OpenSDK you can easily develop your native Selenium & Appium tests (or plug in any of your existing tests), while benefiting from built-in FREE dashboards, local test reports & automated modern CI flows.
Table of Contents – Selenium JavaScript Automation Testing Tutorial For Beginners
- Intro to JavaScript and Selenium
- Prerequisites
- Setting up Node.js
- Installing a Package Manager and Adding a Path Variable
- Create and Run Automation Testing using Selenium JavaScript
Intro to JavaScript and Selenium?
- JavaScript is a text-based programming language used both on the client-side and server-side, allowing you to transform static web pages into interactive ones.
- WebDriver is a remote control interface that enables introspection and control of user agents. It provides a platform and language-neutral wire protocol as a way for out-of-process programs to remotely instruct the behavior of web browsers – WebDriver W3C Recommendation. The cross-platform behavior of web browsers is controlled by web driver. Different web browsers such as Chrome, Firefox, Edge, etc have their own implementation of WebDriver Standards. They all possess browser-specific functionalities using the standard APIs.
- Selenium is an extra wrapper outside the WebDrivers in order to make the WebDriver implementation more smooth and easier for the supporting browsers. For example, if you have Chrome Driver installed on the machine with correct path, Selenium will automatically detect it. The same is the case with other browsers as well. It provides ease to the developers to run the same test script on multiple browser platforms.
Prerequisites
- Node.js (with npm and node installed).
- A package manager for handling open source JavaScript projects.
- Any code editor (I will choose Visual Studio).
- Any internet browser (I will be using Firefox in my case).
Setting up Node.js
Open the command prompt and type ânode -vâ (verifying Node.js is installed):
node -v
Then type ânpm -vâ (verifying npm is installed):
npm -v
If you are not getting these outputs, then you have to install node and npm manually. Click on the following link https://nodejs.org/en/download/ and it will take you to the Node.js official downloads page. Download the version according to the required system you are using. You will see the following page when you click the link given above.
Installing a Package Manager and Adding a Path Variable
Now we are going to set up the package manager for our project which will be âselenium-web driverâ. Just click on the link https://www.npmjs.com/. It will take you to the following page:
In the search bar type ‘selenium-web driver’ and hit enter. You will be taken to the next page where you will find selenium web drivers for different browsers:
Click on Firefox (or whichever browser you would like to use). Then, you’ll see options for different kinds of operating systems you are working on. Simply select the one you are using:
Now we need to set up the path variable for our web driver. In order to do so, just unzip the file in your C directory inside the folder âseleniumWebdriversâ (you have to make a new folder) as seen below:
Copy the above path to your clipboard:
Then go to search and type âenvironmental variablesâ. You will see the following pop-up showing:
Click on it and you will have the following window opened:
Click on environmental variables and you will get to the following window:
Simply select the path and click on the edit button:
You will see this window appearing up:
Click on new and add the path you recently copied and click on the OK button.
Now, go to the folder in the C drive where you put the geckodriver.exe file and open it. You should see this type of output confirming that your path has been set correctly:
Create and Run Automation Testing using Selenium JavaScript
Now that we’ve completed the dependencies part, it’s time to create a JavaScript project and write our first testing code. Go to any directory and create a new project by typing ânpm initâ:
npm init
Then, open the terminal in vs-code or in the command line and type ânpm install selenium-webdriverâ and hit enter. Open the package.json file, it should look like the following:
Now, let’s create a new file with the name âindex.jsâ. This is our time to start writing some code! đȘ
Piece-wise code with explanation:
const {Builder,Buy,Key,util} = require("selenum-webdriver");
In the above Code we are simply pulling out functions from the node module.
async function example() { let driver = await new Builder.forBrowser("firefox").build();
Created the function with the name âexampleâ and waiting for the browser to build and load properly.
await driver.get("http://google.com");
Trying to fetch http://google.com from the browser with our code.
await driver.findElement(By.name("q").sendKeys("Selenium",Key.RETURN));
Sending a search query by the name selenium.
Below is the complete code:
const {Builder,Buy,Key,util} = require("selenum-webdriver"); async function example() { let driver = await new Builder.forBrowser("firefox").build(); await driver.get("http://google.com"); await driver.findElement(By.name("q").sendKeys("Selenium",Key.RETURN)); } example();
In order to run this, go to the terminal and type node index (name of the file in which you put the above code). You should be getting the desired output as below:
We’ve got our first Selenium JavaScript test up and running! đ
I invite you to dive even further to learn some Selenium with JavaScript best practices, and read more content on JavaScript and automation testing in this JavaScript category.
Thanks for the article. However, I am getting an error in the terminal as:
Error: Cannot find module ‘selenum-webdriver’
Can you please help?
Thanks
I noticed it should not be “selenium-webdriver” instead of “selenum”??? (check the first line of given code “require(“selenum-webdriver”);”
I used the word as “selenium-webdriver” but running index.js shows the following error:
(node:21424) UnhandledPromiseRejectionWarning: TypeError: Builder.forBrowser is not a constructor
Help is really appreciated.
Thank you for your comment @usman , Let me share a link from Selenium Documentation:
https://www.selenium.dev/selenium/docs/api/javascript/index.html
I have used the same method and they are also using the same const {Builder, By, Key, until} = require(‘selenium-webdriver’);
Hi Mujtaba
If there is any tutorial with which i can learn Selenium web driver with JavaScript. Can you please share.
Appreciate if you can provide this.
Thanks in advance
Hi SridharK,
https://www.sitepoint.com/how-to-test-your-javascript-with-selenium-webdriver-and-mocha/
This will help you get started writing test cases with Javascript and Selenium.
If you want an easy way with Selenium and Javascript then go for Cypress (https://testautomationu.applitools.com/cypress-tutorial/)
Feel free to discuss more on https://www.linkedin.com/in/mujtabamehdi9
Hi Mujtaba
Thank you so much for sharing this info.
Cypress doesn’t suit to our requirement. Also the other link directly getting into the process of execution.
Appreciate if you can suggest any other tutorial of Selenium with Javascript, which will take me from the beginner level to expert level.
Tutorial should start from set up to advanced level
some thing like https://www.guru99.com/selenium-tutorial.html
Thank you so much in advance.
Hi All
There is a requirement in our project. I should start automating the test cases/scenarios using Selenium webdriver and JavaScript. I searched over the web. Not getting much useful information.
Can any one share the documentation around Selenium with JavaScript. with which one can learn and get to advanced level.
Thanks in advance.
Thanks for this helpful page, but I had to create an account to point out that there are serious errors in your code
Line 1:
Buy -> By
selenum -> selenium
no need to import util
Line 7:
Builder -> Builder()
Line 11:
By.name(“q”).sendKeys -> (By.name(“q”)).sendKeys
Please fix the code, unless its intended as a debugging exercise for the readers. đ
While it’s minor you should change the step where you type in ‘selenium–web driver’ to ‘selenium-wbdriver’ as novices could stumble on this part and not find the next steps as the search result will be something completely different.