DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. End-to-End Test Automation Using Nightwatch

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.

Vishnu V user avatar by
Vishnu V
·
May. 21, 18 · Tutorial
Like (8)
Save
Tweet
Share
30.54K Views

Join the DZone community and get the full member experience.

Join For Free

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

Testing Test automation Hook

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Beginner’s Guide To Styling CSS Forms
  • 10 Things to Know When Using SHACL With GraphDB
  • Custom Validators in Quarkus
  • What Is API-First?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: