NightwatchJS Tutorial: Get Started with Automation Testing

On This Page What is Nighwatch.js Framework?Featur

March 23, 2026 · 9 min read · Testing Guide

NightwatchJS Tutorial: Get Started with Automation Testing

When it comes to automation testing along with, there is one framework that ne'er fails to direct the spotlight and that is NightwatchJS.

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

Overview

Features of Nightwatch.js

  • In-Built Test Runner
  • Browser Automation
  • Test Strategy
  • Cloud Testing Support
  • Distinct Syntax
  • Page Object Support
  • Selenium Server
  • Uninterrupted Integration

How Nightwatch.js Works?

  • Uses a Reposeful HTTP APIfree-base on the W3C WebDriver API (derived from JSONWire protocol).
  • Sends twofold askingto the WebDriver server for browser interactions.
  • First request:Sent to Selenium server to make a session and situate the target element (via CSS or XPath).
  • 2d request:Executes the command or averment on the place web element

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

What is Nighwatch.js Framework?

Nightwatch.jsframework is a Selenium-based test automation fabric, indite inNode.jsand utilize the W3C WebDriver API (erstwhile 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 specification, which is gain from the JSON Wire protocol.

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

Learn More:

Features of Nightwatch.js Framework

Nightwatch.js offers a range of potent features that simplify end-to-end testing and make it easier for teams to build, run, and manage automated examination effectively

  • In-Built Test Runner: It arrive with an inbuilt command-line test runner cortege that helps in executing the machine-driven tests.
  • Browser Automation: Nightwatch.js is an easy-to-use End-to-End testing solution for web-browser covering and websites. It is useful for novice as it is pen in Node.js.
  • Test Strategy: It has the lineament to execute the test 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 prove providers such as.
  • Distinct Syntax: The syntax of Nightwatch.js is simple and yet it is powerful which helps developer to write tests and deliver them in a really short yoke of time.
  • Page Object Support: The framework is easy and simple for beginners to realize as it provides support. It is besides compatible with both CSS and Xpath selectors.
  • Selenium Server: It has the ability to automatically check the with a built-in JUnit XML reporting construction.
  • Continuous Integration: It volunteer full support for Continuous Integration and hence can be easy apply to integrate tests with the continuous build processing system such as TeamCity, Jenkins, Hudson, etc.

Must Read:

Advantages of Nightwatch.js

Nightwatch.js provides several vantage that make it a popular choice for end-to-end testing:

  • Has a full-bodied configuration and a lightweight fabric
  • Can be easily integrated with cloud service supplier like Browserstack for web and peregrine application screen
  • Low code maintenance
  • Improves the test structure
  • Better execution
  • Allows configuration with Cucumber to build a setup.

How does Nightwatch.js work?

In order to found the communicating and relay request, 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 asking to the WebDriver server in order to carry out any kind of browser interaction. This request can be issued with the help of a bid, an asseveration, or an activeness that is available on page objects of the web coating.

  • 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.
  • The 2d postulation performs the actual operation of command or assertion on the web element.

Prerequisites of Nightwatch.js

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

  • Node.js: Nightwatch faculty is establish on top of Node.js, so it clearly indicates that Node.js is required to be establish on the system.
  • Node Package Manager (npm): Once Node.js is successfully installed, the node ’ s package manager i.e. npm should also be instal. 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 install, run the below command to install Nightwatch and save it as a dev dependency.

$ npm install nightwatch -- save-dev

The succeeding step is to install chromedriver/geckodriver and to save it as a dev dependence for running the executing on the require browser.

$ npm install chromedriver -- save-dev

Once all the above steps are execute:

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

Package.json

{'' name '': `` demotest '', '' variation '': `` 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 tryout settings with Nightwatch:

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

nightwatch.conf.js

const chromedriver = require ('chromedriver '); module.exports = {src_folders: [`` tests ''], //tests is a folder in workspace that has the step definition test_settings: {nonremittal: {webdriver: {start_process: true, server_path: chromedriver.path, porthole: 4444, cli_args: [' -- port=4444 ']}, desiredCapabilities: {browserName: 'chrome'}}}};

Writing and Running Nightwatch Tests

We make a JavaScript file named demo.js for scarper a test through Nightwatch with the command. This file needs to be created inside a folder identify “ tests ” as we receive qualify for src_folders in nightwatch.conf.js, shown in the above pace.

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 comment ': 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 bidding.

npm_test.sh

$ npm test

On running this command, it picks the value “ nightwatch ” from “ exam ” key in package.json file that farther hits the nightwatch api to spark 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 event.

It is also a full practice to maintain a separate .js file for page objects which dwell of the locator scheme and selectors of the UI elements.

pageObjects.js

module.exports = {constituent: {googleInputBox: '//input [@ type= '' text ''] ', searchButton: ' (//input [@ value= '' Google Search '']) [2] ', headingText: ` //h3 [contains (textbook (), '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 chooser ';}

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

const chromedriver = require ('chromedriver '); module.exports = {src_folders: [`` test ''], //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: {nonremittal: {webdriver: {start_process: true, server_path: chromedriver.path, port: 4444, cli_args: [' -- port=4444 ']}, desiredCapabilities: {browserName: 'chrome'}}}};

How to use Nightwatch with CucumberJS

is a tool that supports Behavior Driven Development (BDD) and grant us to write tryout in unproblematic English language in Given, When, and Then formatting.

In order to use NightwatchJS with cucumber, we involve to first add cucumber as a dev addiction 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 colony.

package.json

{'' gens '': `` nightwatchdemo '', '' version '': `` 1.0.0 '', '' description '': `` To discover mechanization by nightwatch '', '' main '': `` google.js '', '' scripts '': {'' test '': `` nightwatch '', '' test: cuke '': `` cucumber-js -- need cucumber.conf.js -- require tests -- format node_modules/cucumber-pretty '', '' e2e-test '': `` cucumber-js -- require cucumber.conf.js -- demand step-definition ''}, '' writer '': `` '', '' license '': `` ISC '', '' dependencies '': {'' cuke '': `` ^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 measure is to create a file cucumber.conf.js in the rootage folder that has the setup of part 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 () = & gt; {await startWebDriver (); wait createSession ();}); AfterAll (async () = & gt; {await closeSession (); expect stopWebDriver ();});

Then we create a feature file that has the trial scenarios in Given, When, Then formatting.

google.feature

Feature: Google Search Scenario: Searching Google Given I open Google 's search page Then the title is `` Google '' And the Google search variety exists

It & # 8217; s time to make matching pace definitions utilize in the lineament file for Cucumber to be able to understand and execute the characteristic file. For bestow the feature file, we will create a folder named “ features ” in the project root folder. All the feature files are normally maintain inside this folder.

The undermentioned step would be to create the .js file, this file needs to be under the “ step-definition ” leaflet.

google.js

const {client} = require ('nightwatch-api '); const {Given, Then, When} = require ('cucumber '); Given (/^I exposed Google 's lookup page $ /, () = & gt; {render client.url ('http: //google.com ') .waitForElementVisible ('body ', 1000);}); Then (/^the rubric is `` ([^ ''] *) '' $ /, rubric = & gt; {return client.assert.title (title);}); Then (/^the Google search pattern live $ /, () = & gt; {return client.assert.visible ('input [name= '' q ''] ');});

The next footstep is to create an npm book.

In package.json, we use the npm script to delimit the dictation to execute the Cucumber tests. Here we feature given the name as “e2e-test

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

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

$ npm run e2e-test

Executing Individual Feature Files or Scenarios

Below are some bid for running feature file or scenarios.

For running a individual feature file

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

For running multiple lineament 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 chop-chop with minimal contour and is decipherable as good as very easy to maintain and update. It also supports of cases which proves to be another time-efficient feature of it. On the other hand, Nightwatch-Cucumber besides is a great module for linking the accessibility of Cucumber.js with the robust testing framework of Nightwatch.js.

However, to get the good results while automation testing, it is highly commend to test on a.

Run Nightwatch Tests on Real Device Cloud

Tags
46,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free