E2E Testing with Nightwatch

Written by
Jose Ramirez

E2E Testing validates both your software and its functionality along with external integrations and interfaces in a production-like environment. This article will guide you through the installation, configuration, and implementation of the Nightwatch framework so you can create a simple E2E test suite.

About Nightwatch.js

This open-source automated testing framework will simplify the integration process. It’s built in Node.js, allowing you to write tests even if you don’t have experience –– and if you have written some js code, it’ll be a piece of cake!

Nightwatch uses W3C WebDriver API (Selenium Web driver) to control DOM elements and browser interfaces to make testing as smooth as possible.

Main features

  • Clean Syntax: Effortless test coding with JavaScript (Node.js) and the framework features, using CSS as well as XPath selectors.
  • Built-in Test Runner: Supports sequential or parallel testing in grouped and tagged test suites.
  • WebDrivers Management: Automatic control over Selenium, ChromeDriver, and other WebDrivers in a separate child process to improve performance.
  • Continuous Integration: Can be used with multiple continuous build processes like Jenkins, Teamcity, etc. by using JUnit XML reporting.
  • Cloud Features: Cloud-based cross-browser testing with NightCloud.io, SauceLabs, and BrowserStack.
  • Multiple DOM Selectors Support:  You can select different elements using CSS and XPath selectors, allowing you to run Nightwatch commands over the DOM.

Installation

Before getting started with Nightwatch testing, we will need to set up our environment with NPM & Node.js along with the desired web driver; you can find how to set them up at Node.js.

  • NPM and Node: You can check if already installed by running npm -v and  node -v respectively.
  • WebDriver: The main supported browsers are (Chrome, Firefox, IE, and Safari), You can install and configure them all in the nightwatch.con.js file; in this tutorial, we’ll use chromedriver, which is installed by running npm install chromedriver --save.

Now that you’re in the node folder project, install your dependencies:  run npm install nightwatch --save-dev and npm install chromedriver --save –– once installed, change your test script to nightwatch so your package.json looks like this:

	
{
 "name": "nightwatch-tutorial",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
   "test": "nightwatch"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "chromedriver": "^83.0.0",
   "nightwatch": "^1.3.6"
 }
}
	

Setting Up Nightwatch.js

We’re almost done, but before we start writing some E2E tests, we need to set up Nightwatch and the test folders.

You can create your configuration file two different ways. One is by letting the framework do all the work by running npm run test; this will create a huge file with all possible configurations.

But we’ll go with (for me) the easiest way: create a nightwatch.conf.js file with just the essentials – your test folder, a webdriver path, the default settings, and a screenshot-on-failure feature:

	
module.exports = {
  src_folders: ["tests"],

  webdriver: {
    "start_process": true,
    "server_path": "node_modules/.bin/chromedriver",
    "port": 9515
  },

  test_settings: {
    default: {
      disable_error_log: false,
      launch_url: 'https://nightwatchjs.org',

      screenshots: {
        enabled: false,
        path: 'screens',
        on_failure: true
      },

      desiredCapabilities: {
        browserName : 'chrome'
      },
    },
  }
}
	

Testing Basics

If you’re used to writing tests with other frameworks, Nightwatch testing will seem a little weird because features are called by chaining them (similar to how js async calls with CSS and XPath selectors).

Additionally, remember that each file in the tests folder is a suite that must use the node module.exports; it can have as many steps or validations as you want (in the form of functions as shown below):

	
module.exports = {
  'Landing text testing #1'(browser) {
    const ReactTitleSelector = '.css-159p4b7';
    const ReactSubtitleSelector = "[class=css-1s44ra]";
    const FacebookSignatureSelector = '.css-1izr7si';

    browser
      .url('https://reactjs.org')
      .waitForElementVisible(ReactTitleSelector)
      .assert.containsText(ReactTitleSelector, 'React')
      .waitForElementVisible(ReactSubtitleSelector)
      .assert.containsText(ReactSubtitleSelector, 'JavaScript library')
      .waitForElementVisible(FacebookSignatureSelector)
      .assert.domPropertyEquals(FacebookSignatureSelector, 'alt', 'Facebook Open Source');
  },
}
	

We need to call the browser for every test and then chain all validations, or we can separate the chained calls. Here, we checked the text of some element on the page; since the Facebook signature image didn’t have text, we assert the alt attribute (remember, you can assert any property with the domPropertyEquals).

Testing interactions

Another great E2E testing tool that Nightwatch offers is interactions; this allows us to click, press keys, set values, check if it’s displaying the correct data, main elements are loading, or if it's redirecting properly.

	
module.exports = { 
 'Input data testing #2'(browser) {
   const searchInputSelector = '#algolia-doc-search';
   const searchText = "state";
   const editSelector = '.css-1x091gh';

   browser
     .url('https://reactjs.org')
     .waitForElementVisible(searchInputSelector)
     .setValue(searchInputSelector, searchText)
     .waitForElementVisible('.ds-dataset-1')
     .keys(browser.Keys.ENTER)
     .assert.containsText(editSelector, 'Edit')
     .click(editSelector)
     .assert.urlContains('https://github.com/reactjs/reactjs.org/blob/master/content/docs/')
     .pause(1000)
 }
}
	

There’s a lot more features that I won’t be able to include in this post, but you can check the whole suite Nightwatch API offers; just plug it in your testing chain.

Nightwatch Hooks

Last but not least, hooks are one of my favorites tools to create testing suites. It makes the whole process smoother, you can use them for basic applications like sending messages, logging, and even some asynchronous tasks. You can also use them to take the interaction even deeper; for example, you can use data to log in, check data keys plus other main elements, and log out afterward –– isn’t that great?

Here’s a basic hook:

	
module.exports = {
 'Input data testing #2'(browser) {
   const searchInputSelector = '#algolia-doc-search';
   const searchText = "state";
   const editSelector = '.css-1x091gh';

   browser
     .url('https://reactjs.org')
     .waitForElementVisible(searchInputSelector)
     .setValue(searchInputSelector, searchText)
     .waitForElementVisible('.ds-dataset-1')
     .keys(browser.Keys.ENTER)
     .assert.containsText(editSelector, 'Edit')
     .click(editSelector)
     .assert.urlContains('https://github.com/reactjs/reactjs.org/blob/master/content/docs/')
     .pause(1000)
 },

 after: function (browser, done) {
   browser.end(function () {
     console.log("Test completed, ending browser connection");
     done();
   });
 },
}
	

Give it a Try!

I can’t stress enough how important it is to test your software from top to bottom. E2E testing is a great way to do it, and Nightwatch.js will take it to another level. Now that you know the basics, give it a try!