Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

End-to-End Test Automation Using Nightwatch

DZone's Guide to

End-to-End Test Automation Using Nightwatch

Learn to use Nightwatch, an automated testing and continuous integration framework, as an end-to-end browser testing solution.

· DevOps Zone ·
Free Resource

Automatic continuous monitoring keeps continuous deployment pipelines flowing smoothly and efficiently. Try Instana APM to automatically monitor containers and microservices!

Nightwatch is an automated testing and continuous integration framework based on Node.js and Selenium WebDriver. It is a complete browser (End-to-End) testing solution. It can be used for writing Node.js unit tests.

Nightwatch uses JavaScript language (Node.js) and CSS/XPath to identify an element. It has Built-in command-line test runner which can run the tests either sequentially or in parallel, together, by group, tags or by single.

Installation

Step 1:Download and Install Java.

Step 2:Install Node.js.

Step 3: Install Nightwatch. In the command line, navigate to any directory and type npm install nightwatch.

Step 4: Create a folder structure as shown below where Project is the root.

Image title

Step 5: Copy the Nightwatch folder (which was downloaded using cmd) and place it in Project/lib/nightwatch path.

Step 6: Open the Node directory (C:\Program Files\nodejs\node_modules). Copy the "npm" folder and place it in the Project/lib.

Step 7: Download Selenium Server. Place selenium-server-standalone-{VERSION}.jar in Project/lib/selenium.

Step 8: Download WebDriver (Browser Driver) (Chrome is used in the example) and place it in the lib folder (Project/lib) directory.

Step 9: In the root folder, create “nightwatch.js” file and place the following line: require('E:/Project/lib/nightwatch/bin/runner.js');

Step 10: In the root folder, create the configuration file (nightwatch.json) as mentioned below

{
  "src_folders" : ["tests"],
  "output_folder" : "reports",
  "custom_commands_path" : "",
  "custom_assertions_path" : "",
  "selenium" : {
    "start_process" : true,
"server_path" : "lib/selenium/selenium-server-standalone-3.9.1.jar",
    "log_path" : "",
    "host" : "127.0.0.1",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "lib/chromedriver.exe",
    } },
   "test_settings" : {
   "default" : {
      "launch_url" : "http://localhost",
      "selenium_port"  : 4444,
      "selenium_host"  : "localhost",
      "silent": true,
      "screenshots" : {
        "enabled" : true,
        "path" : "reports",
"use_xpath": true
      },
    "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      } },
 "chrome" : {
      "desiredCapabilities": {
       "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    }
  }
}


Step 11: Navigate to “test” folder and write the following code and save it as “newToursCss.js”

module.exports = {
  'Login test new tours': function (client) {
    client
      .url('http://newtours.demoaut.com/')
      .setValue('input[name="userName"]', 'mercury')
      .setValue('input[name="password"]', 'mercury')
      .click('input[name="login"]')
      .assert.title('Find a Flight: Mercury Tours:')
      .end()    
    }
};

Step 12: Open cmd and Navigate to C:\Project> and type the command node .\nightwatch.js .\tests\NewToursCss.js  

If everything goes well, the browser opens, and in the cmd output should be:

Image title

XPath Selector

By default, Nightwatch uses CSS selector,  in order to use  XPath  location strategy use useXpath() method and useCss() method for switching to CSS location strategy:

module.exports = {
'Login Sales': function (client) {
    client
      .url('https://login.salesforce.com/?locale=in')
      .assert.visible('input[name="pw"]') //tagname[attributename=value]
      .assert.visible('img#logo') // if id is present tag#id
      .useXpath()
      .assert.visible('//input[@name="Login"]')
      .setValue('//input[@type="email"]','v')
      .useCss()
      .waitForElementVisible('input[name="pw"]' ,30000)
      .end();
  }
};


BDD Expect Assertion

Nightwatch uses BDD style assertion library which improves the readability and flexibility of assertions:

module.exports = {
  'BDD EXPECT' : function (client) {
    client
    .url('https://login.salesforce.com/?locale=in')
    .pause(1000);

    // expect element  to be present in 1000ms
    client.expect.element('body').to.be.present.before(1000);

    // expect element <body> to have css property 'display'
    client.expect.element('body').to.have.css('display');

    // expect element <#username> to be an input tag
   client.expect.element('#username').to.be.an('input');

    // expect element <#username> to be visible
    client.expect.element('#username').to.be.visible;

    client.end();

  }
};


Test Hooks

Using before[Each] and after[Each] Hooks

Nightwatch uses before/after and beforeEach/afterEach hooks in tests. The before and after will run before and after the execution of the test suite while beforeEach and afterEach run before and after each test case.

module.exports = {
before : function(browser) {
    var assert = require('assert');
    console.log('Before Suite');
    browser
    .url('http://newtours.demoaut.com/')
    .windowMaximize()
  },
after : function(browser) {
    console.log('after Suite');
    browser
    .end
  },
beforeEach : function(browser) {
 console.log('before test case');
 },
afterEach : function() {
console.log('after testcase');
 },
 'step one' : function (browser) {
  browser
    .waitForElementVisible('body', 1000)
    .setValue('input[name="userName"]', 'mercury')
    .setValue('input[name="password"]', 'mercury')
    .click('input[name="login"]')
  },
 'step two' : function (browser) {
    browser
   .useXpath()
   .click("//a[text()='SIGN-OFF']")

  }
};

Output:

Image title

Global Hooks 

Instead of writing individual hooks for a suite, the hooks can be configured globally and are run before and after test suites and test cases.

In order to use the Global hook:

Step 1: Create a Global.js file in the root folder and write appropriate functionalities:

module.exports = {
   before : function(cb) {
      console.log('GLOBAL BEFORE')
      cb();
    },

    beforeEach : function(browser, cb) {
      //console.log('GLOBAL beforeEach')
      cb();
    },

    after : function(cb) {
      //console.log('GLOBAL AFTER')
      cb();
    },

    afterEach : function(browser, cb) {
      console.log('GLOBAL afterEach')
      cb();
   },

 };


Step 2: Configure the nightwatch.json file.

Add the variable "globals_path" : "Global.js"

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

"globals_path" : "Global.js",

"selenium" : {
"start_process" : true,
"server_path" : "lib/selenium/selenium-server

Run any program to see the global hooks.

Capturing Screenshots

Screenshots can be captured by using  .saveScreenshot() 

module.exports = {
'Login Sales': function (client) {
    client
      .url('https://login.salesforce.com/?locale=in')
      .assert.visible('input[name="pw"]') 
      .assert.visible('img#logo') 
      .useXpath()
      .assert.visible('//input[@name="Login"]')
      .setValue('//input[@type="email"]','v')
      .useCss()
      .waitForElementVisible('input[name="pw"]' ,30000)
      .saveScreenshot('./reports/sales.png')
     .end();
  }
};

The screenshot will appear in the reports folder in the project directory:

sales

Automatic real-time observability is critical to getting the full benefit of CI/CD. Hear @DevOpsDon discuss how Franklin American Mortgage Company cut their new application deployment time from 6-12 months to 2 weeks with the help of Instana APM.

Topics:
nightwatch ,e2e ,testing ,devops

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}