FullStack Labs

Please Upgrade Your Browser.

Unfortunately, Internet Explorer is an outdated browser and we do not currently support it. To have the best browsing experience, please upgrade to Microsoft Edge, Google Chrome or Safari.
Upgrade
Welcome to FullStack Labs. We use cookies to enable better features on our website. Cookies help us tailor content to your interests and locations and provide many other benefits of the site. For more information, please see our Cookies Policy and Privacy Policy.

E2E Testing with Nightwatch

Written by 
Jose Ramirez
,
Senior Software Engineer
E2E Testing with Nightwatch
blog post background
Recent Posts
Six Ways to Handle Concurrency in the JVM
Is there value in learning Vanilla JavaScript?
How to be efficient in remote design work in multicultural teams

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.

Table of contents

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();
   });
 },
}
	

If you’re curious about how hooks really work and how you can use them not only for testing but also coding and developing, my colleague Adam Burdette from Fullstack Labs has an amazing article on it here.

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!

Jose Ramirez
Written by
Jose Ramirez
Jose Ramirez

I started working with apps to complete AI coding challenges with my friends at university. I love being able to take new ideas in creative directions and get things done for my users. I'm a passionate, dedicated leader, and I've built solutions in facial recognition, natural language processing, and logistics. As someone who works with AI, I love Python for the breadth of its machine learning packages, but I also enjoy React Native for its potential to make any kind of mobile app imaginable. I enjoy rock climbing, running, and doing CrossFit.

People having a meeting on a glass room.
Join Our Team
We are looking for developers committed to writing the best code and deploying flawless apps in a small team setting.
view careers
Desktop screens shown as slices from a top angle.
Case Studies
It's not only about results, it's also about how we helped our clients get there and achieve their goals.
view case studies
Phone with an app screen on it.
Our Playbook
Our step-by-step process for designing, developing, and maintaining exceptional custom software solutions.
VIEW OUR playbook
FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project.
Engagements start at $75,000.

company name
name
email
phone
Type of project
How did you hear about us?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.