Selenium with Javascript

Posted on Posted in Javascript Selenium

Why Selenium with JavaScript?

Recently Javascript, NodeJS has gained a real fast-paced momentum.  We hear about lot of JS frameworks getting popular and dominating existing languages and frameworks.  To name a few popular JS Frameworks

  1. NodeJS
  2. AngularJS
  3. ReactJS
  4. BackboneJS
  5. KnockoutJS
  6. and many more…

Reason that Javascript is becoming language of choice is because it makes Web Development (Front End, Backend and Testing) easier to learn as we no more have to learn different languages for backend (like PHP, ASP.NET, Python Django, J2EE etc) and front end.

In this tutorial, we are going to take a look at what a test case will look like with JavaScript and Selenium.

Machine Setup

The first step to write Javascript based code is to install necessary tools so that we can execute the code written in Javascript.  Following basic setup will be enough to get started

  1. Download and Install NodeJS
  2. Download and Install Notepad++ or any simple Editor that provides Syntax Highlighting and Nice Indentation.
  3. Download and Install Firefox Browser.

Project Creation

Like with any other language – Java/C#/CPP we create our projects to begin with.  Here also we will accomplish the same task – But using command prompt.

Open the command prompt and type in following commands

  1. md selproject
  2. cd selproject
  3. npm init

npm init starts a wizard in command prompt that asks bunch of questions.  Keep pressing enter to accept all the defaults. This will create a file named package.json in current folder. That’s our project file.

Installing Dependencies

Now we’ve a project, We should be downloading our dependencies – Selenium and Mocha to be used in Javascript code that we’ll write.  To do that type in following commands in the same command prompt [Make sure you are in the same directory where package.json was created.  i.e. selproject]

npm install -g mocha

npm install –save selenium-webdriver

Creating our first test script

We are done with our setup.  Let’s create the first script that simply launches a browser and takes us to home page and then exits the browser.

In Notepad++, create a new file with following code typed into it.  Save the file to firstTest.js

Running the Code

Once we’ve saved the code written into a file.  We can run it by typing in following command

node firstTest.js

This should launch the browser and wait for it to exit with a delay of 30 seconds.  So that we can notice the browser launch.  Otherwise, this happens at a lightening speed, which is another benefit of using Javascript over C# or Java.


Congratulations!! You’ve just completed and ran your first Selenium Test with Javascript.  

Head on to coding a full fledged working test case.