App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide NightwatchJS Tutorial: Get Started with Automation Testing

NightwatchJS Tutorial: Get Started with Automation Testing

By The Nerdy Geek, Community Contributor -

Table of Contents

When it comes to automation testing along with Selenium and Javascript, there is one framework that never fails to take the spotlight and that is NightwatchJS.

Nightwatch.js is an open-source automated testing framework that is powered by Node.js and provides complete E2E (end to end) solutions to automation testing with Selenium Javascript be it for web apps, browser apps, and websites.

This NightwatchJS tutorial will help you explore its advantages and how it can be installed for flawless automation testing.

What is Nighwatch.js Framework?

Nightwatch.js framework is a Selenium-based test automation framework, written in Node.js and uses the W3C WebDriver API (formerly Selenium WebDriver).  It works by communicating over a restful HTTP API with a WebDriver server (such as ChromeDriver or Selenium Server). The protocol is defined by the W3C WebDriver spec, which is derived from the JSON Wire protocol.

It is a complete end-to-end testing solution that aims to simplify writing automated tests. And effortlessly sets up the way for Continuous Integration.

Features of Nightwatch.js Framework

  • In-Built Test Runner: It comes with an inbuilt command-line test runner suite that helps in executing the automated tests.
  • Browser Automation: Nightwatch.js is an easy-to-use End-to-End testing solution for web-browser applications and websites. It is useful for beginners as it is written in Node.js. 
  • Test Strategy: It has the feature to execute the tests efficiently and can be performed in multiple ways such as sequentially, parallelly, or in groups, and tags.
  • Cloud Testing Support: Nightwatch.js is compatible with different cloud testing providers such as BrowserStack.
  • Distinct Syntax: The syntax of Nightwatch.js is simple and yet it is powerful which helps developers to write tests and deliver them in a very short span of time.
  • Page Object Support: The framework is easy and simple for beginners to understand as it provides Page Object Model support. It is also compatible with both CSS and Xpath selectors. 
  • Selenium Server: It has the ability to automatically control the standalone Selenium server with a built-in JUnit XML reporting structure.
  • Continuous Integration: It offers good support for Continuous Integration and hence can be easily used to integrate tests with the continuous build processing systems such as TeamCity, Jenkins, Hudson, etc.

Advantages of Nightwatch.js

  • Has a robust configuration and a lightweight framework
  • Can be easily integrated with cloud service providers like Browserstack for web and mobile application testing
  • Low code maintenance
  • Improves the test structure
  • Better performance
  • Allows configuration with Cucumber to build a BDD (Behaviour Driven Development) setup.

How does Nightwatch.js work?

In order to establish the communication and relay requests, Nightwatch.js employs a restful HTTP API with the help of an HTTP protocol laid down by the W3C WebDriver API and extracted from the JSONWire protocol. It communicates over a restful HTTP API by utilizing the HTTP protocol that is defined by W3C WebDriver API and derived from the JSONWire protocol.

Nightwatch.js issues dual requests to the WebDriver server in order to carry out any kind of browser interaction. This request can be issued with the help of a command, an assertion, or an action that is available on page objects of the web application.

  • The first request is sent to the Selenium server, for creating a session with the browser. It locates the target element on which the action has to be performed, with the help of CSS or XPath selector of that object.

NightwatchJS - Selenium Request

  • The second request performs the actual operation of command or assertion on the web element.

NightwatchJS - Second Request

Prerequisites of Nightwatch.js

Below are some basic prerequisites that are required to get started with NightwatchJS:

  • Node.js: Nightwatch module is built on top of Node.js, so it clearly indicates that Node.js is required to be installed on the system.
  • Node Package Manager (npm): Once Node.js is successfully installed, the node’s package manager i.e. npm should also be installed. Now, to install the latest version using the npm command-line tool, the below command is executed (here ‘g’ is for installing globally):
$ npm install -g nightwatch

Once, npm is installed, run the below command to install Nightwatch and save it as a dev dependency.

$ npm install nightwatch --save-dev

The next step is to install chromedriver/geckodriver and to save it as a dev dependency for running the execution on the required browser.

$ npm install chromedriver --save-dev

Once all the above steps are done:

Create a Package.json file for the test settings and dependencies

Package.json

{
"name": "demotest",
"version": "1.0.0",
"description": "NightwatchJS Practise test",
"main": "index.js",
"scripts": {
"test": "nightwatch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"chromedriver": "^101.0.0",
"nightwatch": "^2.1.4"
}
}

Create a nightwatch.conf.js for webdriver and test settings with Nightwatch:

nightwatch.conf.js

const chromedriver = require('chromedriver');

module.exports = {
src_folders : ["tests"], //tests is a folder in workspace that has the step definitions
test_settings: {
default: {
webdriver: {
start_process: true,
server_path: chromedriver.path,
port: 4444,
cli_args: ['--port=4444']
},
desiredCapabilities: {
browserName: 'chrome'
}
}
}
};

Writing and Running Nightwatch Tests

We create a JavaScript file named demo.js for running a test through Nightwatch with the command. This file needs to be created inside a folder named “tests” as we have specified for src_folders in nightwatch.conf.js, shown in the above step.

demo.js

//demo.js is a JS file under tests folder
module.exports = {
'step one: navigate to google' : function (browser) { //step one
browser
.url('https://www.google.com')
.waitForElementVisible('body', 1000)
.setValue('input[type=text]', 'nightwatch')
.waitForElementVisible('input[name=btnK]', 1000)
},

'step two: click input' : function (browser) { //step two
browser
.click('input[name=btnK]')
.pause(1000)
.assert.containsText('#main', 'Night Watch')
.end(); //to close the browser session after all the steps
}
}

Next, we run the below command.

npm_test.sh

$ npm test

On running this command, it picks the value “nightwatch” from “test” key in package.json file that further hits the nightwatch api to trigger the URL in chromedriver.

Also, there can be one or more than one step in demo.js(step definition js) file as per the requirement of the test cases.

It is also a good practice to maintain a separate .js file for page objects which consists of the locator strategy and selectors of the UI elements.

pageObjects.js

module.exports = {
elements: {
googleInputBox: '//input[@type="text"]',
searchButton: '(//input[@value="Google Search"])[2]',
headingText: `//h3[contains(text(),'Nightwatch.js')]`
}
}

The locator strategy is set to CSS and Xpath to inspect the UI elements.

async_function.sh

locateStrategy: async function (selector) { return await selector.startsWith('/') ? 'xpath' : 'css selector'; }

Nightwatch.conf.js file is also updated with the page_objects location.

const chromedriver = require('chromedriver');

module.exports = {
src_folders : ["tests"], //tests is a folder in workspace that has the step definitions
page_objects_path: 'page_objects/', //page_objects folder where selectors are saved
test_settings: {
default: {
webdriver: {
start_process: true,
server_path: chromedriver.path,
port: 4444,
cli_args: ['--port=4444']
},
desiredCapabilities: {
browserName: 'chrome'
}
}
}
};

How to use Nightwatch with CucumberJS

Cucumber is a tool that supports Behavior Driven Development (BDD) and allows us to write tests in simple English language in Given, When, and Then format.

In order to use NightwatchJS with cucumber, we need to first add cucumber as a dev dependency in the code.

$ npm install --save-dev nightwatch-api nightwatch @cucumber/cucumber chromedriver cucumber-pretty

The below package.json can be used next for the test settings and dependencies.

package.json

{
"name": "nightwatchdemo",
"version": "1.0.0",
"description": "To learn automation by nightwatch",
"main": "google.js",
"scripts": {
"test": "nightwatch",
"test:cucumber": "cucumber-js --require cucumber.conf.js --require tests --format node_modules/cucumber-pretty",
"e2e-test": "cucumber-js --require cucumber.conf.js --require step-definition"
},
"author": "",
"license": "ISC",
"dependencies": {
"cucumber": "^5.1.0",
"cucumber-pretty": "^1.5.0"
},
"devDependencies": {
"chromedriver": "^2.40.0",
"nightwatch": "^2.1.4",
"nightwatch-api": "^2.2.0"
}
}

After this, we need to create nightwatch.js.conf file.

nightwatch.conf.js

const chromedriver = require('chromedriver');

module.exports = {
test_settings: {
default: {
webdriver: {
start_process: true,
server_path: chromedriver.path,
port: 4444,
},
desiredCapabilities: {
browserName: 'chrome'
}
}
}
};

The next step is to create a file cucumber.conf.js in the root folder that has the setup of starting and closing the webdriver sessions.

cucumber.conf.js

const { setDefaultTimeout, AfterAll, BeforeAll } = require('cucumber');
const { createSession, closeSession, startWebDriver, stopWebDriver } = require('nightwatch-api');

setDefaultTimeout(60000);

BeforeAll(async () => {
await startWebDriver();
await createSession();
});

AfterAll(async () => {
await closeSession();
await stopWebDriver();
});

Then we create a feature file that has the test scenarios in Given, When, Then format.

google.feature

Feature: Google Search

Scenario: Searching Google

  Given I open Google's search page

  Then the title is "Google"

  And the Google search form exists

It’s time to create matching step definitions used in the feature file for Cucumber to be able to understand and execute the feature file. For adding the feature file, we will create a folder named “features” in the project root folder. All the feature files are usually maintained inside this folder.

The following step would be to create the .js files, this file needs to be under the “step-definition” folder.

google.js

const { client } = require('nightwatch-api');
const { Given, Then, When } = require('cucumber');

Given(/^I open Google's search page$/, () => {
return client.url('http://google.com').waitForElementVisible('body', 1000);
});

Then(/^the title is "([^"]*)"$/, title => {
return client.assert.title(title);
});

Then(/^the Google search form exists$/, () => {
return client.assert.visible('input[name="q"]');
});

The next step is to create an npm script.

In package.json, we use the npm script to define the commands to execute the Cucumber tests. Here we have given the name as “e2e-test

"scripts": {
"e2e-test": "cucumber-js --require cucumber.conf.js --require step-definitions"
},

Now, trigger the following command from the terminal to run the tests
npm_run.js

$ npm run e2e-test

Executing Individual Feature Files or Scenarios

Below are some commands for running feature files or scenarios.

For running a single feature file

npm run e2e-test -- features/file1.feature

For running multiple feature files

npm run e2e-test -- features/file1.feature features/file2.feature

For running a Scenario by its line number

npm run e2e-test -- features/my_feature.feature:3

NightwatchJS automates the entire test suite quickly with minimal configuration and is readable as well as very easy to maintain and update. It also supports parallel testing of cases which proves to be another time-efficient feature of it. On the other hand, Nightwatch-Cucumber also is a great module for linking the accessibility of Cucumber.js with the robust testing framework of Nightwatch.js.

However, to get the best results while automation testing, it is highly recommended to test on a real device cloud.

Run Nightwatch Tests on Real Device Cloud

Tags
Automation Frameworks Automation Testing Selenium

Featured Articles

Nightwatch vs Protractor vs Mocha : The Preferred Testing Framework

Accelerate CI/CD pipelines with Parallel Testing

Test Automation using Selenium and Cucumber Framework: Tutorial