Selenium Using JavaScript with chrome driver

To test my web application, I'm using web browser automation. Getting this set up on Windows took a bit of trial and error, so I've documented the process for future reference.

Here's the list of tools you'll need to get up and running: 

  • Java 
  • Selenium 
  • Chromedriver 
  • NodeJS 
  • selenium-webdriver via npm 
Installing the tools
Selenium runs on Java, so if you don't it installed yet, download it from http://www.java.com/en/download/manual.jsp.
Check that Java is installed, by running the following from a command prompt: c:\>java -version
Here's what I get:



C:\Users\andrew>java -version 
java version "1.7.0_45" 
Java(TM) SE Runtime Environment (build 1.7.0_45-b18) 
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode) 

Next, you need to get Selenium. It's enough to simply download the "selenium-server-standalone" jar file from https://code.google.com/p/selenium/downloads/list. At the time of writing, the latest version was selenium-server-standalone-2.37.0.jar.

To allow Selenium to control Chrome, you'll need the "chromedriver", available from here: http://chromedriver.storage.googleapis.com/index.html. At the time of writing, the latest version was 2.7.

Copy the selenium-server-standalone jar file and chromedriver.exe into your project's directory. Open a new command prompt, change to your project directory and then start Selenium with the following command: 

c:\myproject>java -jar selenium-server-standalone-2.35.0.jar -Dwebdriver.chrome.driver=chromedriver.exe

The server can be stopped by pressing Ctrl+C.
To run JavaScript-based tests, you'll need to have NodeJS installed. Download the installer from http://nodejs.org/.

Once NodeJS is installed, you can use the Node Package Manager (npm) to install the selenium-webdriver library: c:\myproject>npm install selenium-webdriver
A basic browser automation script
You can now create JavaScript files that will automate Chrome. Here's a simple script, test.js.

var webdriver = require("selenium-webdriver");
function createDriver() {
var driver = new webdriver.Builder().usingServer('http://localhost:4444/wd/hub').withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().timeouts().setScriptTimeout(10000);
return driver;
}
var driver = createDriver();
driver.get("http://www.google.com");
driver.getTitle().then(function (title) {
console.log(title);
});
driver.quit();


Make sure the Selenium server is running. Then run the script at the command prompt, using node: 
c:\myproject>node test.js

You will see Chrome open and load the Google home page. It will then quit, and at the command prompt you'll see the page title printed.