How to Setup Selenium on Node Environment
Tags: node, javascript
Published: 2020-04-18 08:15:48

*Your guide to setting up and using Selenium with Node*

[Selenium](http://selenium.dev) is one of the most powerful testing suites with a bunch of tools commonly used for testing purposes. It basically opens up a web page automatically in the web browser and provides useful tools for checks page contents for errors, and/or inducing interaction with the page like clicking on buttons, entering input data and so on.

Selenium has a suite of tools that includes: Selenium IDE, Selenium WebDriver, Selenium Grid, and Selenium Standalone Server.

Selenium WebDriver is a free, open-source, portable software-testing framework for testing web applications quickly. It provides a common application programming interface (API) for browser automation.

Its simply a library that you call from your code, which executes your commands on the browser of your choice.

One of the good things about Selenium is, developers can write tests for Selenium WebDriver in any of the programming languages supported by the Selenium project, including Java, C#, Ruby, Python, and JavaScript (named Bindings). 

In this article, we'll explore how to install and setup Selenium/Selenium Webdrive for testing on the node environment. We will also look at how to integrate your local testing environment with third-party tools like BrowserStack, SauceLabs and test runner like Mocha.

# Getting Started

The first thing we need to do is to set up a new NPM project and install our testing library. We'll be using a library called `selenium-webdriver` which is the official library for using Selenium on node environment. There are other alternatives like Webdriver.io and Nightwatch.js

```bash
mkdir node_testing && cd node_testing
npm init -y
npm install selenium-webdriver
```

The next thing to do is to download the right web driver for the browser you will be testing on. You can find details of the list of available web drivers and where to download them from this [page](https://www.npmjs.com/package/selenium-webdriver). In this article, we'll be showing both Firefox and Chrome, as they are available on almost all Operating Systems.

Head over to the [GeckoDriver (for Firefox)](https://github.com/mozilla/geckodriver/releases/) or [ChromeDriver](http://chromedriver.storage.googleapis.com/index.html) driver page and download the latest driver for your operating system. Unzip it content into somewhere fairly easy to navigate to, like the root of your home user directory.
Then the next thing is to add the chrome driver or gecko driver's location to your system PATH variable and it should be an absolute path from the root of your home directory, to the directory containing the drivers. 

For instance, if you are on Linux and your username is toby, and the downloaded driver is placed in the root of your home directory, the path would be `/home/toby` and it was Mac Os it would be `/Users/toby`. 

To set your Path in Linux/Mac OS you need to add the export command to the terminal profile you are using.

If you are using Bash terminal you can open `.bash_profile` (or `.bashrc`) file and `.zshrc` if you are using ZSH. To open the files, you need to use your terminal or head over to the file and edit it manually.

If you want to use your terminal, open your terminal and use any of the below commands:

```bash
$ open .bashrc
or 
$ nano .bashrc
```

After opening it, paste the below at the end of the file:

```bash
#Add WebDriver browser drivers to PATH
#export PATH=$PATH:<driver_path>
export PATH=$PATH:/home/toby
```

Once that's done, save and close the file, then restart your terminal to apply the changes. To confirm if your new path is in the PATH variable do `echo $PATH` and see what's printed in the terminal.

To set your PATH in Windows, you will, first of all, get the path where the driver is download and use the System Environment windows to load your paths. You should watch the below video:

{% youtube zFF6Y8x51JQ %}

To test if your driver is set PATH successfully, you can try running the name of the driver in your terminal:

```bash
chromedriver
```

You should get something like below:

![chromedriver](https://cdn-images-1.medium.com/max/1600/1*0ZkjylC04mogdQqrKCSFAg.png)

Once you have successfully set up your PATH, the next thing is to see how to write and run selenium tests on Node using the Webdriver or Selenium Grid.

# Using Selenium Web Driver

In the npm project, we created earlier, create a new file, give it any name `selenium_test.js` and open it in any code editor of your choice.

Now let's run a simple Selenium Webdriver test. The script below will open a chrome browser, input a term, submit the form, and return the page title. If the test is successful, then it should print out `Test passed`.

```js
const webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;

const driver = new webdriver.Builder()
    .forBrowser('chrome')
    .build();
driver.get('http://www.google.com').then(function(){
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver\n').then(function(){
    driver.getTitle().then(function(title) {
      console.log(title)
      if(title === 'webdriver - Google Search') {
         console.log('Test passed');
      } else {
         console.log('Test failed');
      }
     driver.quit();
    });
  });
});
```

To run the script, in your terminal, ensure you are inside your project directory, then run the below command:

```bash
node selenium_test.js
```

Then if there's no error, you should see an instance of Chrome or Firefox browser opening up, navigating to google.com and search the term web driver. Then finally it should print out Test passed when all goes well.

# Using Selenium Grid (Remote Testing)

Selenium Grid is a part of the Selenium Suite that helps in running multiple tests across different browsers, operating systems, and machines in parallel. Selenium Grid is a smart proxy server that allows Selenium tests to route commands to remote web browser instances.

Below are some third party integrations of Selenium grid:

## On BrowserStack

You can run your Selenium Test remotely using Selenium Grid on BrowserStack. [BrowserStack](https://www.browserstack.com/) gives you immediate access to the Selenium Grid of 2000+ real devices and desktop browsers. Running your Selenium tests with NodeJS on BrowserStack is quite simple.

Running Selenium tests on BrowserStack requires a username and an access key. To obtain your username and access keys, you'll need to [sign up for a Free Trial](https://www.browserstack.com/users/sign_up).

Once you have acquired your access keys, let's see how to run our tests on BrowserStack.

First, you'll need to decide on the OS and Device/Browser combination you'd like to test on.

In the same project directory, create a new file called `selenium_grid_test.js` and open it in your code editor:

```js
const webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;
var capabilities = {
 'browserName' : 'Chrome',
 'browser_version' : '81.0',
 'os' : 'Windows',
 'os_version' : '10',
 'resolution' : '1024x768',
 'browserstack.user' : 'USERNAME',
 'browserstack.key' : 'ACCESS_KEY',
 'name' : 'Bstack-[Node] Sample Test'
}
var driver = new webdriver.Builder().
  usingServer('http://hub-cloud.browserstack.com/wd/hub').
  withCapabilities(capabilities).
  build();
driver.get('http://www.google.com').then(function(){
  driver.findElement(webdriver.By.name('q')).sendKeys('webdriver\n').then(function(){
    driver.getTitle().then(function(title) {
      console.log(title);
      if(title === 'webdriver - Google Search') {
         console.log('Test passed');
      } else {
         console.log('Test failed');
      }      
      driver.quit();
    });
  });
});
```

You'll need to replace the `USERNAME` and `ACCESS_KEY` with your username and your access key.

To run the script, open up your terminal and run node `selenium_grid_test.js`. 
This should have opened a URL, input a search term `webdriver`, submitted the form and returned the page title. The results will be displayed in your terminal like before and now on the BrowserStack Automate dashboard, where you can see Text Logs, Screenshots of every Selenium command, and a Video Recording of your entire test.

## On Sauce Labs

[SauceLabs](http://saucelabs.com) works similarly to BrowserStack and uses Selenium Grid to run selenium tests remotely.

To rewrite the tests above in BrowserStack:

```js
const webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until,
    username = "USERNAME",
    accessKey = "ACCESS_KEY";
let driver = new webdriver.Builder()
    .withCapabilities({
      'browserName': 'chrome',
      'platform': 'Windows XP',
      'version': '43.0',
      'username': username,
      'accessKey': accessKey
    })
    .usingServer("https://" + username + ":" + accessKey +
          "@ondemand.saucelabs.com:443/wd/hub")
    .build();
driver.get('http://www.google.com');
driver.findElement(By.name('q')).sendKeys('webdriver');
driver.sleep(1000).then(function() {
  driver.findElement(By.name('q')).sendKeys(webdriver.Key.TAB);
});
driver.findElement(By.name('btnK')).click();
driver.sleep(2000).then(function() {
  driver.getTitle().then(function(title) {
    console.log(title);
    if(title === 'webdriver - Google Search') {
      console.log('Test passed');
    } else {
      console.log('Test failed');
    }
  });
});
driver.quit();
```

From your Sauce Labs user settings, you can get your user name and access key. Replace the `USERNAME` and `ACCESS_KEY` in the variable with your actual user name and access key values.

To run your tests, open your terminal in the project directory and run:

```bash
node saucelabs_test.js
```

This should tun your tests and the result will be shown in your terminal. Just like Browserstack, if you go to your [Sauce Labs dashboard page](https://saucelabs.com/beta/dashboard/tests), you'll see all your tests listed; from there you'll be able to see videos, screenshots, and other such data of each test.

# Using Mocha (Test Runner) With Selenium

[Mocha](http://mochajs.com) is a testing framework that can be used to run multiple test case scenarios in Selenium. It simply a library that helps you run code, where you'll be able to point out the part with the issue, also gives the coverage of code as a way of knowing what code impacts what tests.

Mocha comes with a bunch of testing features and power with its simple API interface and makes writing unit tests much easier.

To start using mocha, all you need is to install it and write some test:

```bash
npm install --save-dev mocha
```

Run the above command on the terminal in your project directory to install Jest.

Now create `mocha_test.js` file:

```js
const webdriver = require('selenium-webdriver');
const { until } = require('selenium-webdriver');
const { By } = require('selenium-webdriver');
const assert = require('assert');

describe('webdriver', () => {
    let driver;
    before(async () => {
      driver = new webdriver.Builder().forBrowser('chrome')
      .build();
     
      await driver.get(`https://google.com`);
    }, 30000);
  
    after(async () => {
      await driver.quit();
    }, 40000);
  
    it('test google search', async () => {

        await driver.findElement(webdriver.By.name('q')).sendKeys('webdriver\n')
        
        const title = await driver.getTitle()
        console.log(title)
        assert.equal(title, "webdriver - Google Search")
    }, 35000);
  });
```

To run the tests, we can now do:

```bash
node mocha_test.js
```

Once that's done you should be able to see the results of the tests printed out one after the other in terminal.

# Using TestCraft With Zero Code

[TestCraft](http://testcraft.io) is a powerful test automation platform for regression and continuous testing, as well as monitoring of web applications. All these are possible without a single line of code.

[TestCraft](http://testcraft.io) is built on Selenium and makes you write your automated tests with zero code. With TestCraft, you can visually create automated, Selenium-based tests using a drag and drop interface, and run them on multiple browsers and work environments, simultaneously. No coding skills needed to get started.

It also has support for End to End testing with any OS, Device or Browser you want to test on. You can basically run your tests on multiple platforms with a single push of a button.

To start using TestCraft, you'll first of all need to Sign up for a free trial.

With TestCraft, you'll be able to:

*Create a Custom Test Scenarios*: Using the Drag and Drop tool, you can easily create test flows and scenarios depending on what part of the web app you want to test.

*Run Tests on Multiple Platforms*: After writing and building your tests, right from TestCraft you can run your tests simultaneously on multiple platforms, environments, and devices.

*Produce Comprehensive Reports*: After running your tests, TestCraft is able to produce comprehensive reports of how your tests perform and what parts needed to be fixed. These reports usually include videos and screenshots pointing out the part with errors and needed fixing.

*Fixes Tests Using AI*: TestCraft has a unique feature of using AI to automatically fix any broken tests due to changes in your web application to reduce back and forth on development and testing.

# Conclusion

In this article, we have been able to explore various ways to use selenium on Node Environment. Additionally, it is also possible to integrate Selenium and related tools like Sauce Labs and BrowserStack with continuous integration (CI) tools like CircleCI.

We have also seen how we can write and run tests on multiple platforms simultaneously without writing a single code using just TestCraft.
If you enjoyed this article, kindly clap and share it with others.