October 19, 2020 Jonny Steiner

Test Your Browsers with our Overview of Nightwatch.JS

Share this knowledge!

Nightwatch.js is a powerful end-to-end testing and browser automation framework that is growing in popularity. The tool is based on node.js and powered by the W3C WebDriver API. With clear syntax, inbuilt test runner, WebDriver Services, cloud testing support, and continuous integration, Nightwatch.js enables developers to easily perform browser automation and test on various types of apps and websites.

History and Main Concepts

Nightwatch.js was created by Andrei Rusu in January 2014 to run automated UI tests. The name ‘Nightwatch’ comes from the famous Rembrandt painting from the 17th century, ‘Nightwatch’. Within a quick time, it became a popular node.js test automation framework. In 2017, the tool featured in 2017 ThoughtWorks Technology Radar.

Nightwatch.js comes with a built-in test runner that enables you to run tests in parallel or in a sequential mode. The syntax is pretty simple and clear. You can quickly write tests using node.js and Xpath selectors and CSS and perform end-to-end testing with ease. The tool has its own cloud testing platform called Nightcloud.io. You can also run your tests on other cloud testing platforms such as our own SeeTest.

Nightwatch.js is also known as a Selenium wrapper as it works in tandem with the Selenium server for browser automation. Using Selenium, you can easily automate different browsers. WebDriver services run as a separate child process. With the support for Xpath selectors and CSS, you can easily identify page objects and elements. The tool can be easily integrated with continuous integration server tools such as Jenkins, Hudson, and TeamCity. The assertion framework extends to support custom assertions and commands.

Installation

To use Nightwatch.js, you need to install Java and Node.js on your machine.

Step 1: Install Java

Visit this link to download and install Java:

https://www.oracle.com/in/java/technologies/javase-downloads.html

Download the .exe file, double-click it and follow the instructions of the wizard to install Java on the machine.

Step 2: Configure Environment Variables

To use Java, you should first add the Java path to environment variables.

To do so, go to System -> Advanced System Settings -> Advanced > Environment variables

Under User variables:

  • Name: JAVA_HOME
  • Path: C:\Program Files\Java\jdk-14.0.2 (JDK Folder path on your machine)

Under system variables:

  • Path: C:\Program Files\Java\jdk-14.0.2\bin (Java bin folder path on your machine)

To check if Java is successfully installed and working fine, open the command prompt and type the following command: java -version

nightwatch.js java version

You can see Java JDK and JRE details. It means Java is working fine.

Step 3: Install Node.js

To install Node.js, visit this link:

https://nodejs.org/en/download/

The latest LTS version is 12.19.0. It comes with npm 6.14.8.

node.js

After the .msi file downloads, double-click it to begin the installation procedure.

node.js setup

Click on Next.

node.js license

Accept the license agreement and click next.

node.js next

Choose the folder where you want to install Node.js and click next.

node.js folder

Choose the features you want to install along with Node.js runtime and click next.

node.js tools

To compile native modules, you might need additional tools. When you select the check-box, it will install the necessary tools.

node.js install

When you click Install and the installation process begins.

node.js installation

Click Finish when the process is completed.

node.js finished

To check if Node.js and npm are successfully installed, open the command prompt, and type the following commands:

  • node–v
  • npm–v

node.js npm

You can see the version of npm and Node.js. It means they are successfully installed.

Step 4: Install Nightwatch.js

To download the Nightwatch.js end-to-end testing framework, open the command prompt and type the following command:

  • npm install Nightwatch –save-dev

It will start installing Nightwatch.js.

nightwatch.js install

When the process is done, it will display the details of the installation.

nightwatch.js done

Step 5: Install Selenium standalone server

You need Selenium Server for browser automation. To download the Selenium server, visit this link:

https://www.selenium.dev/downloads/

The latest Selenium standalone server version is 3.141.59. Download the jar file and create a bin folder in your project directory and save it in that folder.

Step 6: Install Chromedriver

To implement the W3C WebDriver protocol, you need the ChromeDriver. To download ChromeDriver, visit this link:

https://sites.google.com/a/chromium.org/chromedriver/downloads

Check your chrome version and download the corresponding file. Save the file in the bin folder of your project.

Configuring Nightwatch.js

Now that the installation process is done, you need to configure the tool so that it can find the test scripts, selenium server, and Chromedriver.

So, create a JSON file called nightwatch.json file and add the following configuration settings to that file. The settings include the Selenium standalone server path, ChromeDriver path, tests folder, and reports folder.

 

{
  "src_folders" : ["tests"],
  "output_folder" : "reports",

  "selenium" : {
    "start_process" : true,
    "server_path" : "./bin/selenium-server-standalone-3.141.59.jar",
    "log_path" : "",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "./bin/chromedriver.exe"
    }
  },

  "test_settings" : {
    "default" : {
      "launch_url" : "http://localhost",
      "selenium_port"  : 4444,
      "selenium_host"  : "localhost",
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    }
  }
}

Running your First Test with Nightwatch.js

Now that the framework is ready, you can run your first test. Create a Java class file and run it using the framework.

Open notepad and save it as a .js extension in the tests folder (eg: ExperitestSearch.js). Now add the following code to the js file.

 

module.exports = {
'@tags': ['google'],
  'Demo test Experitest' : function (browser) {
    browser
      .url('http://www.ecosia.org')
      .waitForElementVisible('body')
      .assert.titleContains('Ecosia')
      .assert.visible('input[type=search]')
      .setValue('input[type=search]', 'Experitest')
      .assert.visible('button[type=submit]')
      .click('button[type=submit]')	
      .end()
  }
}

 

Before running this test script, you need to edit the package.json file. When you install Nightwatch.js, it will automatically create a package.json file. Else, you can create it manually.

To create it manually, open the command prompt and type the following command:

  • npm init

Now, open the package.json file and add the following code under ‘scripts’:

“scripts”: {

    “test”: “nightwatch”

Now, run the test script from the command prompt by typing the following command:

  • npm run test

nightwatch.js

The test script opens the Chrome browser and opens the Ecosia search engine. It then searches for the term ‘Experitest’, displays the search results, and closes the browser.

As you can see from the test results, Nightwatch clearly reports about each step, the time taken for that step, and whether it has passed or not.

If one of the assertions is not passed, it will display it with an error mark and also mentions the reason for the failure.

Here is an example of a test script that has a failed assertion:

nightwatch.js failed assertion

Here you can see that 1 assertion failed, 1 error, and 2 passed. The reason for the failure is that element <input[type=search]> could not be located.

Running Nightwatch tests in SeeTest Cloud

Running one or two tests on your local machine is easy. When you have to test your scripts on multiple browsers/platforms, you need a cloud testing platform. SeeTest from Experitest is a powerful cloud test automation platform that enables you to test your scripts on a variety of devices, browsers, and platforms located in different geographic locations.

To do so, create a nightwatch.conf.js file and add the following code into it:

 

module.exports = (function(settings) {
  console.log(settings["test_settings"]["default"])

  if (process.env.LT_ACCESS_KEY) {
    settings["test_settings"]["default"]["access_key"] = process.env.LT_ACCESS_KEY;
  }
  if (process.env.SELENIUM_HOST) {
	settings.selenium.host = process.env.SELENIUM_HOST;
  }
  if (process.env.SELENIUM_PORT) {
	settings.selenium.host = process.env.SELENIUM_PORT;
  }
  return settings;
})(require('./nightwatch.json'));

 

In addition, you need to edit the Nightwatch JSON file to add the SeeTest cloud URL, access key, and desired capabilities.

To get your access key, log in to your SeeTest account and click on your account. Click on ‘Get access key’. Copy the key and save it on your machine.

nightwatch.js seetest

Now, open the Nightwatch JSON file and add the following settings to it:

{
  "src_folders" : ["./tests"],
  "output_folder" : "./reports",
   "globals_path" : "nightwatch.conf.js",
  "test_workers": {
	"enabled": true,
	"workers": "auto"
  },
  "selenium" : {
	"start_process" : false,
	"server_path" : "",
	"log_path" : "",
	"host" : "https://cloud.seetest.io/wd/hub",
	"port" : 80,
    "cli_args" : {
  	"webdriver.chrome.driver" : "",
  	"webdriver.ie.driver" : "",
  	"webdriver.firefox.profile" : ""
	}
  },
  "test_settings" : {
	"default" : {
  	"launch_url" : "http://google.com",
  	"selenium_port"  : 80,
  	"selenium_host"  : "https://cloud.seetest.io/wd/hub",
  	"silent": false,
  	"screenshots" : {
    	"enabled" : true,
    	"path" : ""
  	},

  	"access_key" : "Enter your access key heere",
 
  	"skip_testcases_on_fail": false,
  	
  	"desiredCapabilities": {
       "build":"Nightwatch-Selenium--Test",
   	"platform" : "Windows 10",
   	"browserName" : "Chrome",
    	"version" : "78.0",
    	"selenium_version" : "3.13.0",
   	"visual":true,
    	"video":true,
    	"console":true,
    	"geoLocation" : "IN",
    	"chrome.driver" : "78.0",
    	"network":true
  	}
	},
	"chrome": {
  	"desiredCapabilities": {
    	"platform": "Windows 10",
        "browserName": "chrome",
    	"version": "78.0"
  	}
	},
	"safari" : {
  	"desiredCapabilities": {
    	"platform": "macos 10.13",
    	"browserName": "safari",
    	"version": "11.0"
  	}
	},
	"firefox" : {
  	"desiredCapabilities": {
    	"platform": "win10",
    	"browserName": "firefox",
    	"version": "60"
  	}
	},
	"edge" : {
  	"desiredCapabilities": {
    	"platform": "Windows 10",
    	"browserName": "MicrosoftEdge",
    	"version": "17.0"
  	}
	}
  }
}

 

Now, you can run the test from the command prompt.

nightwatch.js command prompt

Summary of Nightwatch.JS

Nightwatch.js is a powerful end-to-end test automation framework that enables you to quickly write and execute your test scripts. It can be easily integrated with 3rd party cloud solutions which means you can run your tests on hundreds of platforms versions and browsers versions. The tool uses an iterator to retry failed tests up to 3 times. By allowing you to write modules of tests, the tool enables you to import these modules without rewriting those test cases. For instance, you can use the same login module for multiple test cases. Browser automation is made easy as the tool automatically starts and stops the Selenium server. Overall, Nightwatch.js is a handy tool that lets you quickly write your end-to-end testing scripts while giving the flexibility to extend them later.

Guy ArieliCTO

Share this knowledge!