Nightwatch.jsNightwatch.js

Browser automated testing done easy.

Write End-to-End tests in Node.js quickly and effortlessly that run against a Selenium server.

Browser Automation

Nightwatch.js is an easy to use Node.js based End-to-End (E2E) testing solution for browser based apps and websites. It uses the powerful Selenium WebDriver API to perform commands and assertions on DOM elements.

Main Features

  • Clean syntax

    Simple but powerful syntax which enables you to write tests very quickly, using only Javascript (Node.js) and CSS or Xpath selectors.

  • Selenium server

    Controls the Selenium standalone server automatically in a separate child process; can be disabled if Selenium runs on another host.

  • CSS & Xpath support

    Either CSS or Xpath selectors can be used to locate and verify elements on the page or execute commands.

  • Easy to extend

    Flexible command and assertion framework which makes it easy to extend to implement your application specific commands and assertions.

  • Built-in test runner

    Built-in command-line test runner which can run the tests either sequentially or in parallel, together, by group, tags or single. Grunt support is built-in.

  • Cloud services support

    Works with cloud testing providers, such as SauceLabs and BrowserStack.

  • Continous integration support

    JUnit XML reporting is built-in so you can integrate your tests in your build process with systems such as Teamcity, Jenkins, Hudson etc.

Demo Test

The test below navigates to google.com and searches for "rembrandt van rijn", then verifies if the term first result is the Wikipedia page of Rembrandt.


module.exports = {
  'Demo test Google' : function (client) {
    client
      .url('http://www.google.com')
      .waitForElementVisible('body', 1000)
      .assert.title('Google')
      .assert.visible('input[type=text]')
      .setValue('input[type=text]', 'rembrandt van rijn')
      .waitForElementVisible('button[name=btnG]', 1000)
      .click('button[name=btnG]')
      .pause(1000)
      .assert.containsText('ol#rso li:first-child',
        'Rembrandt - Wikipedia')
      .end();
  }
};

Stay Updated

Follow @nightwatchjs on Twitter to receive updates or to get in touch.

Follow on Twitter

Developer Guide

What is Nightwatch?

Nightwatch.js is an automated testing framework for web applications and websites, written in Node.js and using the Selenium WebDriver API.

It is a complete browser automation (End-to-End) solution which aims to simplify the process of setting up Continous Integration and writing of automated tests.

Nightwatch got its name from the famous painting The Night Watch by Dutch painter Rembrandt van Rijn. The masterpiece is prominently displayed in the Rijksmuseum, in Amsterdam - The Netherlands.

Overview of Selenium

Selenium is a very popular and comprehensive set of tools for browser automation, initially written for Java but now with support for most programming languages.

Selenium's main projects are:

Nightwatch uses the Selenium WebDriver, specifically the WebDriver Wire Protocol to perform the browser automation related tasks.

Theory of Operation

Nightwatch works by sending HTTP requests to the Selenium server with the right parameters and interpreting the response. The restful API protocol is defined by the Selenium JsonWireProtocol. See below for an example workflow for browser initialization.

Theory of Operation

Most of the times, Nightwatch needs to send at least 2 requests to the Selenium server in order to perform a command or assetion, the first one being the request to locate an element given a CSS selector (or Xpath expression) and the next to perform the actual command/assertion on the given element.

Install Node.js

From nodejs.org:

"Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices."

There are installation packages and instructions for most major Operating systems on its website nodejs.org. Remember to install also the npm tool, which is the node package manager and is distributed with the Node.js installer.

Install Nightwatch

To install the latest version using the npm command line tool, run the following:

$ npm install nightwatch

To make nightwatch runner available globally in your system, add the -g option after npm install and sudo if you're on Mac OS X / Linux or other Unix based OS.

Running the Selenium Server

The Selenium WebDriver server is simply a Java servlet which runs separately on the machine with the browser you want to test.

Download Selenium

Download the latest version of the selenium-server-standalone-{VERSION}.jar file from the Selenium downloads page and place it on the computer with the browser you want to test. In most cases this will be on your local machine and typically inside your project's source folder.

A good practice is to create a separate subfolder (e.g. bin) and place it there as you might have to download other driver binaries if you want to test multiple browsers.

Running Selenium Automatically

If the server is on the same machine where Nightwatch is running, it can be started/stopped directly by the Nightwatch Test Runner.

Running Selenium Manually

To run the selenium server manually, from the directory with the jar run the following:

$ java -jar selenium-server-standalone-{VERSION}.jar

More info about running the Selenium server can be found here:
http://code.google.com/p/selenium/wiki/RemoteWebDriverServer

For viewing all the run-time options, run the previous command adding the -help:

$ java -jar selenium-server-standalone-{VERSION}.jar -help

The test runner expects a configuration file to be passed, using by default a nightwatch.json file from the current directory, if present. Let's create one in the project's root folder.

The nightwatch.json file will look like this:

{
  "src_folders" : ["tests"],
  "output_folder" : "reports",
  "custom_commands_path" : "",
  "custom_assertions_path" : "",
  "page_objects_path" : "",
  "globals_path" : "",

  "selenium" : {
    "start_process" : false,
    "server_path" : "",
    "log_path" : "",
    "host" : "127.0.0.1",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "",
      "webdriver.ie.driver" : ""
    }
  },

  "test_settings" : {
    "default" : {
      "launch_url" : "http://localhost",
      "selenium_port"  : 4444,
      "selenium_host"  : "localhost",
      "silent": true,
      "screenshots" : {
        "enabled" : false,
        "path" : ""
      },
      "desiredCapabilities": {
        "browserName": "firefox",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    },

    "chrome" : {
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    }
  }
}

Basic settings

Name type default description
src_folders string|array none An array of folders (excluding subfolders) where the tests are located.
output_folder
Optional
string tests_output The location where the JUnit XML report files will be saved.
custom_commands_path Optional string|array none Location(s) where custom commands will be loaded from.
custom_assertions_path Optional string|array none Location(s) where custom assertions will be loaded from.
page_objects_path
Optional since v6.0.1
string|array none Location(s) where page object files will be loaded from.
globals_path
Optional since v0.4.8
string none Location of an external globals module which will be loaded and made available to the test as a property globals on the main client instance.

Globals can also be defined/overwritten inside a test_settings environment.
selenium
Optional
object An object containing Selenium Server related configuration options. See below for details.
test_settings object This object contains all the test related options. See below for details.
live_output
Optional
boolean false Whether or not to buffer the output in case of parallel running. See below for details.
disable_colors
Optional
boolean false Controls whether or not to disable coloring of the cli output globally.
parallel_process_delay
Optional
integer 10 Specifies the delay(in milliseconds) between starting the child processes when running in parallel mode.
test_workers
Optional since v0.7.0
boolean|object false Whether or not to run individual test files in parallel. If set to true, runs the tests in parallel and determines the number of workers automatically.
If set to an object, can specify specify the number of workers as "auto" or a number.

Example: "test_workers" : {"enabled" : true, "workers" : "auto"}

Selenium settings

Below are a number of options for the selenium server process. Nightwatch can start and stop the Selenium process automatically which is very convenient as you don't have to manage this yourself and focus only on the tests.

If you'd like to enable this, set start_process to true and specify the location of the jar file inside server_path.

Name type default description
start_process boolean false Whether or not to manage the selenium process automatically.
start_session
since v0.6.1
boolean true Whether or not to automatically start the Selenium session.
server_path string none The location of the selenium jar file. This needs to be specified if start_process is enabled.
E.g.: lib/selenium-server-standalone-2.43.0.jar
log_path string|boolean none The location where the selenium output.log file will be placed. Defaults to current directory.
To disable Selenium logging, set this to false
host string 127.0.0.1 Usually not required and only used if start_process is true. Specify the IP address you wish Selenium to listen on.
port integer 4444 The port number Selenium will listen on.
cli_args
since v0.5.1
object none List of cli arguments to be passed to the Selenium process. Here you can set various options for browser drivers, such as:

  • webdriver.firefox.profile: Selenium will be default create a new Firefox profile for each session. If you wish to use an existing Firefox profile you can specify its name here.
    Complete list of Firefox Driver arguments available here.
  • webdriver.chrome.driver: Nightwatch can run the tests using Chrome browser also. To enable this you have to download the ChromeDriver binary and specify it's location here. Also don't forget to specify chrome as the browser name in the desiredCapabilities object.
    More information can be found on the ChromeDriver website.
  • webdriver.ie.driver: Nightwatch has support for Internet Explorer also. To enable this you have to download the IE Driver binary and specify it's location here. Also don't forget to specify "internet explorer" as the browser name in the desiredCapabilities object.

Test settings

Below are a number of options that will be passed to the Nightwatch instance. You can specify multiple groups of options so you could have different values per environment:

{
  ...
  "test_settings" : {
    "default" : {
      ...
    },
    "integration" : {
      ...
    }
  }
}

A "default" environment is required. All the other environments are derived from default and their settings can be overridden as needed.

The key of the settings group can be passed then to the runner as the --env argument to use the specified settings, like so:

$ nightwatch --env integration

This can be useful if you need to have different settings for your local machine and the Continuous Integration server.

Name type default description
launch_url string none A url which can be used later in the tests as the main url to load. Can be useful if your tests will run on different environments, each one with a different url.
selenium_host string localhost The hostname/IP on which the selenium server is accepting connections.
selenium_port integer 4444 The port number on which the selenium server is accepting connections.
silent boolean true Whether to show extended Selenium command logs.
output boolean true Use to disable terminal output completely.
disable_colors
since v0.4.13
boolean false Use to disable colored output in the terminal.
firefox_profile
deprecated
string|boolean none This options has been deprecated in favor of the cli_args object on the selenium settings object.
chrome_driver
deprecated
string none This options has been deprecated in favor of the cli_args object on the selenium settings object.
ie_driver
deprecated
string none This options has been deprecated in favor of the cli_args object on the selenium settings object.
screenshots object none Selenium generates screenshots when command errors occur. With on_failure set to true, also generates screenshots for failing or erroring tests. These are saved on the disk.

Since v0.7.5 you can disable screenshots for command errors by setting "on_error" to false.

Example:

"screenshots" : {
  "enabled" : true,
  "on_failure" : true,
  "on_error" : false,
  "path" : ""
}
username string none In case the selenium server requires credentials this username will be used to compute the Authorization header.

The value can be also an environment variable, in which case it will look like this:
"username" : "${SAUCE_USERNAME}"
access_key string none This field will be used together with username to compute the Authorization header.

Like username, the value can be also an environment variable:
"access_key" : "${SAUCE_ACCESS_KEY}"
desiredCapabilities object An object wich will be passed to the Selenium WebDriver when a new session will be created. You can specify browser name for instance along with other capabilities.
Example:

"desiredCapabilities" : {
  "browserName" : "firefox",
  "acceptSslCerts" : true
}

You can view the complete list of capabilities here.
globals
since v0.4.8
object An object wich will be made available within the test and can be overwritten per environment. Example:

"globals" : {
  "myGlobal" : "some_global"
}
exclude
since v0.4.9
array An array of folders or file patterns to be skipped (relative to the main source folder).
Example:

"exclude" : ["excluded-folder"]
or:
"exclude" : ["test-folder/*-smoke.js"]
filter
since v0.5.1
string Folder or file pattern to be used when loading the tests. Files that don't match this patter will be ignored.
Example:

"filter" : "tests/*-smoke.js"
log_screenshot_data boolean false Do not show the Base64 image data in the (verbose) log when taking screenshots.
use_xpath
since v0.5.1
boolean false Use xpath as the default locator strategy
cli_args
since v0.6.1
object none Same as Selenium settings cli_args. You can override the global cli_args on a per-environment basis.
end_session_on_fail
since v0.6.5
boolean true End the session automatically when the test is being terminated, usually after a failed assertion.
skip_testcases_on_fail
since v0.7.0
boolean true Skip the rest of testcases (if any) when one testcase fails..

Writing Tests

Using the preferred CSS selector model to locate elements on a page, Nightwatch makes it very easy to write automated End-to-End tests.

Create a separate folder for tests in your project, e.g.: tests. Each file inside it will be loaded as a test by the Nightwatch test runner. A basic test will look like this:


module.exports = {
  'Demo test Google' : function (browser) {
    browser
      .url('http://www.google.com')
      .waitForElementVisible('body', 1000)
      .setValue('input[type=text]', 'nightwatch')
      .waitForElementVisible('button[name=btnG]', 1000)
      .click('button[name=btnG]')
      .pause(1000)
      .assert.containsText('#main', 'Night Watch')
      .end();
  }
};

Remember always to call the .end() method when you want to close your test, in order for the Selenium session to be properly closed.

A test can have multiple steps, if needed:

module.exports = {
  'step one' : function (browser) {
    browser
      .url('http://www.google.com')
      .waitForElementVisible('body', 1000)
      .setValue('input[type=text]', 'nightwatch')
      .waitForElementVisible('button[name=btnG]', 1000)
  },

  'step two' : function (browser) {
    browser
      .click('button[name=btnG]')
      .pause(1000)
      .assert.containsText('#main', 'Night Watch')
      .end();
  }
};

Tests can also be written in this format:


this.demoTestGoogle = function (browser) {
  browser
    .url('http://www.google.com')
    .waitForElementVisible('body', 1000)
    .setValue('input[type=text]', 'nightwatch')
    .waitForElementVisible('button[name=btnG]', 1000)
    .click('button[name=btnG]')
    .pause(1000)
    .assert.containsText('#main', 'The Night Watch')
    .end();
};

Using XPath selectors

Nightwatch supports xpath selectors also. To switch to xpath instead of css selectors as the locate strategy, in your test call the method useXpath(), as seen in the example below. To switch back to CSS, call useCss().

To always use xpath by default set the property "use_xpath": true in your test settings.


this.demoTestGoogle = function (browser) {
  browser
    .useXpath() // every selector now must be xpath
    .click("//tr[@data-recordid]/span[text()='Search Text']")
    .useCss() // we're back to CSS now
    .setValue('input[type=text]', 'nightwatch')
};

BDD Expect Assertions

Nightwatch introduces starting with version v0.7 a new BDD-style assertion library which greatly improves the flexibility as well as readability of the assertions.

The expect assertions use a subset of the Expect api from the Chai framework and are available for elements only at this point. Here's an example:


module.exports = {
  'Demo test Google' : function (client) {
    client
      .url('http://google.no')
      .pause(1000);

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

    // expect element <#lst-ib> to have css property 'display'
    client.expect.element('#lst-ib').to.have.css('display');

    // expect element  to have attribute 'class' which contains text 'vasq'
    client.expect.element('body').to.have.attribute('class').which.contains('vasq');

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

    // expect element <#lst-ib> to be visible
    client.expect.element('#lst-ib').to.be.visible;

    client.end();
  }
};


The expect interface provides a much more flexible and fluid language for defining assertions, significantly improved over the existing assert interface. The only downside is that it's not possible to chain assertions anymore and at this point custom message aren't yet supported.


For a complete list of available expect assertions, refer to the API docs.

Using before[Each] and after[Each] hooks

Nightwatch provides the standard before/after and beforeEach/afterEach hooks to be used in the tests.

The before and after will run before and after the execution of the test suite respectively, while beforeEach and afterEach are ran before and after each testcase (test step).

All methods have the Nightwatch instance passed as argument.

Example:


module.exports = {
  before : function(browser) {
    console.log('Setting up...');
  },

  after : function(browser) {
    console.log('Closing down...');
  },

  beforeEach : function(browser) {

  },

  afterEach : function(browser) {

  },

  "step one" : function (browser) {
    browser
     // ...
  },

  "step two" : function (browser) {
    browser
    // ...
      .end();
  }
};

In the example above the sequence of method calls will be as follows: before(), beforeEach(), "step one", afterEach(), beforeEach(), "step two", afterEach(), after()

Asynchronous before[Each] and after[Each]

All the before[Each] and after[Each] methods can also perform asynchronous operations, in which case they will require the callback passed as the second argument.

The done function must be called as the last step when the async operation completes. Not calling it will hang the test runner.

Example with beforeEach & afterEach:


module.exports = {
  beforeEach: function(browser, done) {
    // performing an async operation
    setTimeout(function() {
      // finished async duties
      done();
    }, 100);
  },

  afterEach: function(browser, done) {
    // performing an async operation
    setTimeout(function() {
      // finished async duties
      done();
    }, 200);
  }
};

External Globals

In addition to having globals defined in your nightwatch.json, sometimes it's useful to have also an external globals file, specified in the globals_path property.

You can overwrite globals per environment as needed. Say you have your tests running locally and also against a remote cloud selenium server. Most of the times you will need some different setting up.

Example:


module.exports = {
  'local-env' : {
    isLocal : true,
  },

  'remote-env' : {
    isLocal : false
  },

  before: function(done) {
    // run this only for the local-env
    if (this.isLocal) {
      // start the local server
      App.startServer(function() {
        // server listening
        done();
      });
    } else {
      done();
    }
  },

  after: function(done) {
    // run this only for the local-env
    if (this.isLocal) {
      // start the local server
      App.stopServer(function() {
        // shutting down
        done();
      });
    } else {
      done();
    }
  },

  // This will be run before each test suite is started
  beforeEach: function(browser, done) {
    // getting the session info
    browser.status(function(result) {
      console.log(result.value);
      done();
    });
  },

  // This will be run after each test suite is finished
  afterEach: function(browser, done) {
    console.log(browser.currentTest);
    done();
  }
};

You can refer to the provided globalsModule.js for an example.

Test Runner

Nightwatch includes a command-line test runner which makes it easy to run tests and generate useful output.

Example usage:

$ ./nightwatch --test tests/demotest.js

If you have installed nightwatch with-g (global) option you can skip this.

To use the test runner in your project simply create a new file called nightwatch and add the following:

For Linux and MacOSX:
#!/usr/bin/env node
require('nightwatch/bin/runner.js');

Then set the permissions:

$ chmod a+x nightwatch
For Windows:

Name the file nightwatch.js and add the following line:

require('nightwatch/bin/runner.js');

Then run as follows:

C:\workspace\project> node nightwatch.js

Command-line Options

The test runner supports a number of run-time options to be passed at. To view all, run the following:

$ ./nightwatch --help
Name Shortname default description
--config -c ./nightwatch.json The location of the nightwatch.json file - the configuration file which the runner uses and which also includes the Selenium WebDriver options.
--output -o tests_output The location where the JUnit XML reports will be saved.
--reporter -r junit Name of a predefined reporter (e.g. junit) or path to a custom reporter file to use.
--env -e default Which testing environment to use - defined in nightwatch.json
--verbose -v Shows extended selenium command logging during the session
--test -t Runs only the specified test. By default it will attempt to run all tests in the folder and its subfolders.
--testcase Used only together with --test. Runs the specified testcase from the current suite/module.
--group -g Runs only the specified group of tests (subfolder). Tests are grouped by being placed in the same subfolder.
--skipgroup -s Skip one or several (comma separated) group of tests.
--filter -f Specify a filter (glob expression) as the file name format to use when loading the test files.
--tag -a Filter test modules by tags. Only tests that have the specified tags will be loaded.
--skiptags Skips tests that have the specified tag or tags (comma separated).
--retries Retries failed or errored testcases up to the specified number of times.
--suiteRetries Retries failed or errored testsuites up to the specified number of times.

Test Groups

Nightwatch makes it possible to organize your test scripts into groups and run them as needed. To group tests together just place them in the same sub-folder. The folder name is the name of the group.

Example:

lib/
  ├── selenium-server-standalone.jar
custom-commands/
  ├── loginUser.js
  ├── attachPicture.js
tests/
  ├── logingroup
  |   ├── login_test.js
  |   └── otherlogin_test.js
  ├── addressbook
  |   ├── addressbook_test.js
  |   └── contact_test.js
  ├── chat
  |   ├── chatwindow_test.js
  |   ├── chatmessage_test.js
  |   └── otherchat_test.js
  └── smoketests
      ├── smoke_test.js
      └── othersmoke_test.js

To run only the smoketests group you would do the following:

$ nightwatch --group smoketests

Also, if you would want to skip running the smoketests group you would do the following:

$ nightwatch --skipgroup smoketests

To skip multiple groups, just add them as comma-separated:

$ nightwatch --skipgroup addressbook,chat

Test Tags

You can also selectively target tests to run based on tags, such that a test may be belong to multiple tags. For example, you might have a login test that belongs to a login suite as well as a sanity suite.

The tagging can be accomplished by adding thetags property to a test module:


module.exports = {
  tags: ['login', 'sanity'],
  'demo login test': function (client) {
     // test code
  }
};

To select which tags to run, use the --tag command line flag:

$ nightwatch --tag login

Specify multiple tags as:

$ nightwatch --tag login --tag something_else

Parallel Running

Starting with v0.5 Nightwatch supports the tests to be run in parallel. This works by specifying multiple environments in the command line, separated by comma. E.g.:

$ nightwatch -e default,chrome

The above will run two environments named default and chrome in parallel.

Terminal Output

Each environment will be run as a separate child_process and the output will be sent to the main process.

To make the output easier to read, Nightwatch by default buffers the output from each child process and displays everything at the end, grouped by environment.

If you'd like to disable the output buffering and see the output from each child process as it is sent to stdout, simply set the property "live_output" : true on the top level in your nightwatch.json (e.g. after selenium).
You can create a separate environment per browser (by chaining desiredCapabilities) and then run them in parallel. In addition, using the filter and exclude options tests can be split per environment in order to be ran in parallel.

Via Workers

Version v0.7 introduces a new feature which allows the tests to be run in parallel. When this is enabled the test runner will launch a configurable number of child processes and then distribute the loaded tests over to be ran in parallel.

To enable test workers, set the test_workers top-level property, like so:


"test_workers": {
  "enabled": true,
  "workers": "auto"
}   

or, simply:


"test_workers": true 

The workers option configures how many child processes can run concurrently.

  • "auto" - determined by number of CPUs e.g. 4 CPUs means 4 workers
  • {number} - specifies an exact number of workers

Test concurrency is done at the file level. Each test file will fill a test worker slot. Individual tests/steps in a test file will not run concurrently.

Currently test output is not aggregated and may be difficult to follow; this feature would be most useful in a CI environment where stdout matters less. Another limitation is this feature won't work as desired when using Nightwatch for running unit tests.

Using Grunt

Grunt is a popular JavaScript task runner. Starting with version 0.6 Nightwatch is bundled with an easy to use Grunt task which can be used in your existing Grunt-based build configuration for running the tests.

Usage

First, load the Nightwatch grunt task at the top in your Gruntfile.js.


module.exports = function(grunt) {
  var nightwatch = require('nightwatch');
  nightwatch.initGrunt(grunt);

  // ...

};

Task Configuration and Targets

The Nightwatch task will have one more more targets which can be used in various ways, one way being to map them to environments. Available settings are:

  • options - the only available option so far is cwd - current working directory
  • argv - command-line arguments that would normally be passed to the Nightwatch runner (e.g.: env);
  • settings - the test settings specified to a single Nightwatch environment.

Example


grunt.initConfig({
  nightwatch: {
    options: {
      cwd: './'
    },

    'default' : {},

    browserstack: {
      argv: {
        env: 'browserstack'
      },
      settings: {
        silent: true
      }
    },

    'all' : {
      argv: {
        env: 'default,browserstack'
      }
    },
  }
});


Run the task as follows:

$ grunt nightwatch:default
or
$ grunt nightwatch:browserstack


There are also a few third-party Grunt plugins for Nightwatch which can be used instead, if you prefer. The most popular one is grunt-nightwatch.

Using Page Objects

The Page Objects methodology is a popular pattern to write end-to-end tests by wrapping the pages or page fragments of a web app into objects. The purpose of a page object is to allow a software client to do anything and see anything that a human can by abstracting away the underlying html actions needed to access and manipulate the page.

A comprehensive introduction to Page Objects can be found in this article.

As of version 0.7 Nightwatch provides an enhanced and more powerful interface for creating page objects, significantly improved over the previous support. Page objects created prior to v0.7 will still continue to work however we recommend upgrading to the new version.

Configuring Page Objects

To create a page object simply create an object with properties that describe the page. Each page object should be located in a separate file, located in a designated folder. Nightwatch reads the page objects from the folder (or folders) specified in the page_objects_path configuration property.

The page_objects_path property can also be an array of folders, allowing you thus to logically split the page objects into smaller groups.

The Url property

You can optionally add a url property that designates the page's URL. To navigate to the page, you can call the navigate method on the page object.

The URL will usually be defined as a string:


module.exports = {
  url: 'http://google.com'
};

It can also be a function in case the URL is dynamic. One use case for this is to support different test environments. You can create a function that gets called in the context of the page, thus allowing you to do:


module.exports = {
  url: function() { 
    return this.api.launchUrl + '/login'; 
  }
};

Defining Elements

Most of the time, you will want to define elements on your page that your tests will interact with through commands and assertions. This is made simple using the elements property so that all your elements are defined in a single place. Especially in larger integration tests, using elements will go a long way to keep test code DRY.

Switching between css and xpath locate strategies is handled internally so you don't need to call useXpath and useCss in your tests. The default locateStrategy is css but you can also specify xpath:


module.exports = {
  elements: {
    searchBar: { 
      selector: 'input[type=text]' 
    },
    submit: { 
      selector: '//[@name="q"]', 
      locateStrategy: 'xpath' 
    }
  }
};


Using the elements property allows you to refer to the element by its name with an "@" prefix, rather than selector, when calling element commands and assertions (click, etc).

Putting elements and url together, say you have the following defined above saved as a google.js file:


module.exports = {
  url: 'http://google.com',
  elements: {
    searchBar: { 
      selector: 'input[type=text]' 
    },
    submit: { 
      selector: '//[@name="q"]', 
      locateStrategy: 'xpath' 
    }
  }
};


In your tests you will use it as follows:


module.exports = {
  'Test': function (client) {
    var google = client.page.google();

    google.navigate()
      .assert.title('Google')
      .assert.visible('@searchBar')
      .setValue('@searchBar', 'nightwatch')
      .click('@submit');

    client.end();
  }
};

Defining Sections

Sometimes it is useful to define sections of a page. Sections do 2 things:

  • Provide a level of namespacing under the page
  • Provide element-level nesting so that any element defined within a section is a descendant of its parent section in the DOM

You can create sections using the sections property:


module.exports = {
  sections: {
    menu: {
      selector: '#gb',
      elements: {
        mail: { 
          selector: 'a[href="mail"]'
        },
        images: {
          selector: 'a[href="imghp"]'
        }
      }
    }
  }
};


Your tests would use it as follows:


module.exports = {
  'Test': function (client) {
    var google = client.page.google();
    google.expect.section('menu').to.be.visible;

    var menuSection = google.section.menu;
    menuSection.expect.element('@mail').to.be.visible;
    menuSection.expect.element('@images').to.be.visible;

    menuSection.click('@mail');

    client.end();
  }
};


Note that every command and assertion on a section (other than expect assertions) returns that section for chaining. If desired, you can nest sections under other sections for complex DOM structures.

Writing Commands

You can add commands to your page object using the commands property. This is a useful way to encapsulate logic about the page that would otherwise live in a test, or multiple tests.

Nightwatch will call the command on the context of the page or section. Client commands like pause are available via this.api. For chaining, each function should return the page object or section.

In this case, a command is used to encapsulate logic for clicking the submit button:


var googleCommands = {
  submit: function() {
    this.api.pause(1000);
    return this.waitForElementVisible('@submitButton', 1000)
      .click('@submitButton')
      .waitForElementNotPresent('@submitButton');
  }
};

module.exports = {
  commands: [googleCommands],
  elements: {
    searchBar: {
      selector: 'input[type=text]'
    },
    submitButton: {
      selector: 'button[name=btnG]'
    }
  }
};


Then the test is simply:


module.exports = {
  'Test': function (client) {
    var google = client.page.google();
    google.setValue('@searchBar', 'nightwatch')
      .submit();

    client.end();
  }
};

Writing Custom Commands

Most of the time you will need to extend the Nightwatch commands to suit your own application needs. Doing that is only a matter of creating a separate folder and defining your commands in that folder, each one inside its own file.

Then specify the path to that folder inside the nightwatch.json file, as the custom_commands_path property. The command name is the name of the file itself, and it needs to follow the following pattern:


exports.command = function(file, callback) {
  var self = this, imageData, fs = require('fs');

  try {
    var originalData = fs.readFileSync(file);
    var base64Image = new Buffer(originalData, 'binary')
      .toString('base64');
    imageData = 'data:image/jpeg;base64,' + base64Image;
  } catch (err) {
    console.log(err);
    throw "Unable to open file: " + file;
  }

  this.execute(
    function(data) { // execute application specific code
      App.resizePicture(data);
      return true;
    },

    [imageData], // arguments array to be passed

    function(result) {
      if (typeof callback === "function") {
        callback.call(self, result);
      }
    }
  );

  return this; // allows the command to be chained.
};

The example below defines a command (e.g. resizePicture.js) which loads an image file as data-URI and calls a method named resizePicture defined inside the application.

With this command, the test will look something like:


module.exports = {
  "testing resize picture" : function (browser) {
    browser
      .url("http://app.host")
      .waitForElementVisible("body")
      .resizePicture("/var/www/pics/moon.jpg")
      .assert.element(".container .picture-large")
      .end();
  }
};

Writing Custom Assertions

Nightwatch allows you to even define your own assertions, extending the available .assert and .verify namespaces.

Beginning with v0.4 assertions have a very simple interface which is shared between built-in assertions and custom ones. Therefore, custom assertions must implement the following interface:


exports.assertion = function() {

  /**
   * The message which will be used in the test output and
   * inside the XML reports
   * @type {string}
   */
  this.message;

  /**
   * A value to perform the assertion on. If a function is
   * defined, its result will be used.
   * @type {function|*}
   */
  this.expected;

  /**
   * The method which performs the actual assertion. It is
   * called with the result of the value method as the argument.
   * @type {function}
   */
  this.pass = function(value) {

  };

  /**
   * The method which returns the value to be used on the
   * assertion. It is called with the result of the command's
   * callback as argument.
   * @type {function}
   */
  this.value = function(result) {

  };

  /**
   * Performs a protocol command/action and its result is
   * passed to the value method via the callback argument.
   * @type {function}
   */
  this.command = function(callback) {

    return this;
  };

};

Both custom assertions and custom commands inherit from EventEmitter if defined in the form above.
If, however, your command/assertion is defined in the constructor style, then you must inherit manually, similarly to the pause command.

To see some examples, check the assertions module source-code on Github:
/nightwatch/tree/master/lib/selenium/assertions

Custom Reporter

If you'd like to define your own reporter in addition to the built-in ones (stdout and junit-xml) you can do so in two ways:

The --reporter command-line argument

Interface:

module.exports = {
  write : function(results, options, done) {
    done();
  }
};

The reporter method in your external globals file.

See the provided globalsModule.js for an example.

Example:


module.exports = {
  reporter : function(results, done) {
    console.log(results);
    done();
  }
};

Writing Unit Tests

Since version 0.6 it's possible to also write unit or integration tests in Nightwatch for Node.js applications and APIs. This concept is still very new to Nightwatch so bear in mind this feature is not yet as stable or as feature-rich as a mature unit testing framework.

Disabling automatic selenium session

Nightwatch automatically attempts to connect to the specified selenium server and create a session. When running unit tests this needs to be disabled by setting the start_session property to false inside the selenium settings group either on the root level or inside a specific environment.

Assertion framework

The client object bundles the Node.js Assert module, same way as for end-to-end testing. Custom commands and assertions are also loaded and made available, together with globals.

Example

Below there's a unit test for the utils.js Nightwatch module:


var Utils = require('ib/util/utils.js');
module.exports = {
  testFormatElapsedTime : function(client) {
    var test = client.assert;

    var resultMs = Utils.formatElapsedTime(999);
    var resultSec = Utils.formatElapsedTime(1999);
    var resultMin = Utils.formatElapsedTime(122299, true);

    test.equal(resultMs, '999ms');
    test.equal(resultSec, '1.999s');
    test.equal(resultMin, '2m 2s / 122299ms');
  },

  testMakeFnAsync : function(client) {
    function asynFn(done) {
      done();
    }

    function syncFn() {}

    var test = client.assert;

    test.equal(Utils.makeFnAsync(1, asynFn), asynFn);

    var convertedFn = Utils.makeFnAsync(1, syncFn);
    convertedFn(function() {
      test.ok('converted fn called');
    });
  }
};

Asynchronous Unit Tests

The second argument to a test function, if provided, is the done callback which signals the test is complete. If present, the callback must be called when the async operation finishes.

Example

Below there's a unit test for the utils.js Nightwatch module:


module.exports = {
  'demo UnitTest' : function (client, done) {
    client.assert.ok('TEST');

    setTimeout(function() {
      done();
    }, 500);
  }
};

Using Third-party Assertion Frameworks

It's also possible to use a third-party assertion framework for writing tests. The example below uses Chai.


var Utils = require('lib/util/utils.js');
var expect = require('chai').expect;

module.exports = {
  testFormatElapsedTime : function(client) {
    var resultMs = Utils.formatElapsedTime(999);
    var resultSec = Utils.formatElapsedTime(1999);
    var resultMin = Utils.formatElapsedTime(122299, true);

    expect(resultMs).to.equal('999ms');
    expect(resultSec).to.equal('1.999s');
    expect(resultMin).to.equal('2m 2s / 122299ms');
  }
};

Using a Combined Configuration

Below it's an example of how you can combine end-to-end tests and unit tests in the same nightwatch.json configuration file. Notice the usage of exclude and filter properties.

An empty exclude means we want to reset its value and rely only on filter.

{
  "src_folders" : ["./examples/tests", "./examples/unittests"],
  "output_folder" : "./examples/reports",

  "selenium" : {
    "start_process" : true,
    "server_path" : "./bin/selenium-server-standalone.jar",
    "log_path" : "",
    "host" : "127.0.0.1",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "",
      "webdriver.ie.driver" : ""
    }
  },

  "test_settings" : {
    "default" : {
      "launch_url" : "http://localhost",
      "selenium_port"  : 4444,
      "selenium_host"  : "localhost",
      "silent": true,
      "screenshots" : {
        "enabled" : false,
        "path" : ""
      },
      "desiredCapabilities": {
        "browserName": "firefox",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      },
      "exclude" : "./examples/unittests/*"
    },

    "unittests" : {
      "selenium" : {
        "start_process" : false,
        "start_session" : false
      },
      "filter" : "./examples/unittests/*",
      "exclude" : ""
    }
  }
}


API Reference


Nightwatch introduces in version 0.7 a new BDD-style interface for performing assertions on elements, defined on the expect namespace on the main Nightwatch instance. It is based on the Chai Expect assertion library and provides a greater level of flexibility and adds new capabilities over the classic assert interface.

It uses a chainable language to construct assertions given an element specified by a css/xpath selector. A simple example looks like the following:


this.demoTest = function (browser) {
  // start with identifying the element
  // and then assert the element is present
  browser.expect.element('#main').to.be.present;

  // or assert the element is visible
  browser.expect.element('#main').to.be.visible;
};

Language Chains

The following are provided as chainable getters to improve the readability of your assertions. They do not provide testing capabilities and the order is not important.

  • to
  • be
  • been
  • is
  • that
  • which
  • and
  • has
  • have
  • with
  • at
  • does
  • of

.equal(value)/.contain(value)/.match(regex)

These methods will perform assertions on the specified target on the current element. The targets can be an attribute value, the element's inner text and a css property.


this.demoTest = function (browser) {
  browser.expect.element('#main').text.to.equal('The Night Watch');

  browser.expect.element('#main').text.to.contain('The Night Watch');

  browser.expect.element('#main').to.have.css('display').which.equals('block');
};

.not

Negates any of assertions following in the chain.


this.demoTest = function (browser) {
  browser.expect.element('#main').text.to.not.equal('The Night Watch');

  browser.expect.element('#main').text.to.not.contain('The Night Watch');

  browser.expect.element('#main').to.have.css('display').which.does.not.equal('block');
};

.before(ms)/.after(ms)

These methods perform the same thing which is essentially retrying the assertion for the given amount of time (in milliseconds). before or after can be chained to any assertion and thus adding retry capability.

You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) as a global property in your nightwatch.json or in your external globals file. Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).


this.demoTest = function (browser) {
  browser.expect.element('#main').text.to.contain('The Night Watch').before(1000);

  browser.expect.element('#main').text.to.not.contain('The Night Watch').after(500);
};

.a(type) since v0.7

Checks if the type (i.e. tag name) of a specified element is of an expected value.

Arguments:
Name Type description
type string The expected type
Usage:

this.demoTest = function (browser) {
  browser.expect.element('#q').to.be.an('input');
  browser.expect.element('#w').to.be.a('span');
};

.attribute(name) since v0.7

Checks if a given attribute of an element exists and optionally if it has the expected value.

Arguments:
Name Type description
attribute string The attribute name
Usage:

this.demoTest = function (browser) {
  browser.expect.element('body').to.have.attribute('data-attr');
  browser.expect.element('body').to.not.have.attribute('data-attr');
  browser.expect.element('body').to.have.attribute('data-attr').before(100);
  browser.expect.element('body').to.have.attribute('data-attr')
    .equals('some attribute');
  browser.expect.element('body').to.have.attribute('data-attr')
    .not.equals('other attribute');
  browser.expect.element('body').to.have.attribute('data-attr')
    .which.contains('something');
  browser.expect.element('body').to.have.attribute('data-attr')
    .which.matches(/^something\ else/);
};

.css(property) since v0.7

Checks a given css property of an element exists and optionally if it has the expected value.

Arguments:
Name Type description
property string The css property name
Usage:

this.demoTest = function (browser) {
  browser.expect.element('#main').to.have.css('display');
  browser.expect.element('#main').to.not.have.css('display');
  browser.expect.element('#main').to.have.css('display').before(100);
  browser.expect.element('#main').to.have.css('display').which.equals('block');
  browser.expect.element('#main').to.have.css('display').which.contains('some value');
  browser.expect.element('#main').to.have.css('display').which.matches(/some\ value/);
};

.enabled since v0.7

Property that checks if an element is currently enabled.

Usage:

this.demoTest = function (browser) {
  browser.expect.element('#weblogin').to.be.enabled;
  browser.expect.element('#main').to.not.be.enabled;
  browser.expect.element('#main').to.be.enabled.before(100);
};

.present since v0.7

Property that checks if an element is present in the DOM.

Usage:

this.demoTest = function (browser) {
  browser.expect.element('#main').to.be.present;
  browser.expect.element('#main').to.not.be.present;
  browser.expect.element('#main').to.be.present.before(100);
};

.selected since v0.7

Property that checks if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.

Usage:

this.demoTest = function (browser) {
  browser.expect.element('#main').to.be.selected;
  browser.expect.element('#main').to.not.be.selected;
  browser.expect.element('#main').to.be.selected.before(100);
};

.text since v0.7

Property that retrieves the text contained by an element. Can be chained to check if contains/equals/matches the specified text or regex.

Usage:

this.demoTest = function (browser) {
  browser.expect.element('#main').text.to.equal('The Night Watch');
  browser.expect.element('#main').text.to.not.equal('The Night Watch');
  browser.expect.element('#main').text.to.equal('The Night Watch').before(100);
  browser.expect.element('#main').text.to.contain('The Night Watch');
  browser.expect.element('#main').text.to.match(/The\ Night\ Watch/);
};

.value

Property that retrieves the value (i.e. the value attributed) of an element. Can be chained to check if contains/equals/matches the specified text or regex.

Usage:

this.demoTest = function (browser) {
  browser.expect.element('#q').to.have.value.that.equals('search');
  browser.expect.element('#q').to.have.value.not.equals('search');
  browser.expect.element('#q').to.have.value.which.contains('search');
  browser.expect.element('#q').to.have.value.which.matches(/search/);
};

.visible

Property that asserts the visibility of a specified element.

Usage:

this.demoTest = function (browser) {
  browser.expect.element('#main').to.be.visible;
  browser.expect.element('#main').to.not.be.visible;
  browser.expect.element('#main').to.be.visible.before(100);
};

The classic assert/verify library is still available on the Nightwatch instance as two objects containing the same methods to perform assertions on elements:

  • .assert - when an assertion fails, the test ends, skipping all other assertions.
  • .verify - when an assertion fails, the test logs the failure and continues with other assertions.

This will end the test:

client.assert.visible('.non_existing');

But this will just log the failure and continue:

client.verify.visible(".non_existing");

Node.js Assert Module

Nightwatch.js extends Node.js assert module, so you can also use any of the available methods there in your tests.

Automatically retrying failed assertions

You can tell Nightwatch to automatically retry failed assertions until a given timeout is reached, before the test runner gives up and fails the test. This can be accomplished by setting the property retryAssertionTimeout (in milliseconds) in the globals file.

For example: retryAssertionTimeout = 2000

attributeContains

Checks if the given attribute of an element contains the expected value.

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
attribute string The attribute name
expected string The expected contained value of the attribute to check.
message
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.attributeContains('#someElement', 'href', 'google.com');
    
};

attributeEquals

Checks if the given attribute of an element has the expected value.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
attribute string The attribute name
expected string The expected value of the attribute to check.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.attributeEquals("body", "data-attr", "some value");
    
};

containsText

Checks if the given element contains the specified text.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
expectedText string The text to look for.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.containsText("#main", "The Night Watch");
    
};

cssClassPresent

Checks if the given element has the specified CSS class.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
className string The CSS class to look for.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.cssClassPresent("#main", "container");
    
};

cssClassNotPresent

Checks if the given element does not have the specified CSS class.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
className string The CSS class to look for.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.cssClassNotPresent("#main", "container");
    
};

cssProperty

Checks if the specified css property of a given element has the expected value.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
cssProperty string The CSS property.
expected string|number The expected value of the css property to check.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.cssProperty("#main", "display", "block");
    
};

elementPresent

Checks if the given element exists in the DOM.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.elementPresent("#main");
    
};

elementNotPresent

Checks if the given element does not exist in the DOM.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.elementNotPresent(".should_not_exist");
    
};

hidden

Checks if the given element is not visible on the page.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.hidden(".should_not_be_visible");
    
};

title

Checks if the page title equals the given value.

Parameters:
Name Type description
expected string The expected page title.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.title("Nightwatch.js");
    
};

urlContains since v0.5.1

Checks if the current URL contains the given value.

Parameters:
Name Type description
expectedText string The value expected to exist within the current URL.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.urlContains('google');
    
};

urlEquals since v0.5.1

Checks if the current url equals the given value.

Parameters:
Name Type description
expected string The expected url.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.urlEquals('http://www.google.com');
    
};

value

Checks if the given form element's value equals the expected value.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
expectedText string The expected text.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.value("form.login input[type=text]", "username");
    
};

valueContains

Checks if the given form element's value contains the expected value.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
expectedText string The expected text.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.valueContains("form.login input[type=text]", "username");
    
};

visible

Checks if the given element is visible on the page.

Parameters:
Name Type description
cssSelector string The CSS selector used to locate the element.
msg
Optional
string Optional log message to display in the output. If missing, one is displayed by default.
Usage:

this.demoTest = function (browser) {
  
  browser.assert.visible(".should_be_visible");
    
};

The commands are convenience methods for performing various operations on the page and usually incorporate two or more Selenium protocol actions.

The callback function

Each method below allows an optional callback argument to be passed as the last argument. The callback function will then be called after the command is completed with the main instance as the context and the response object as argument.


this.demoTest = function (browser) {
  
  browser.click("#main ul li a.first", function(response) {
    this.assert.ok(browser === this, "Check if the context is right.");
    this.assert.ok(typeof response == "object", "We got a response object.");   
  });
    
};

clearValue

Clear a textarea or a text input element's value. Uses elementIdValue protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (client) {
  client.clearValue('input[type=text]');
};

click

Simulates a click event on the given DOM element. Uses elementIdClick protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (client) {
  client.click("#main ul li a.first");
};

closeWindow since v0.3.0

Close the current window. This can be useful when you're working with multiple windows open (e.g. an OAuth login).
Uses window protocol command.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (client) {
  client.closeWindow();
};

deleteCookie since v0.4.0

Delete the cookie with the given name. This command is a no-op if there is no such cookie visible to the current page.

Arguments:
Name Type description
The cookieName name of the cookie to delete.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function(browser) {
  browser.deleteCookie("test_cookie", function() {
    // do something more in here
  });
}

deleteCookies since v0.4.0

Delete all cookies visible to the current page.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function(browser) {
  browser.deleteCookies(function() {
    // do something more in here
  });
}

end

Ends the session. Uses session protocol command.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (browser) {
  browser.end();
};

getAttribute

Retrieve the value of an attribute for a given DOM element. Uses elementIdAttribute protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
atttribute string The attribute name to inspect.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
* The value of the attribute
Usage:

this.demoTest = function (client) {
  client.getAttribute("#main ul li a.first", "href", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value, "#home");
  });
};

getCookie since v0.4.0

Retrieve a single cookie visible to the current page. The cookie is returned as a cookie JSON object, as defined here.

Uses cookie protocol command.

Arguments:
Name Type description
name string The cookie name.
callback function The callback function which will receive the response as an argument.
Returns
Type description
object|null The cookie object as a selenium cookie JSON object or null if the cookie wasn't found.
Usage:

this.demoTest = function(browser) {
  browser.getCookie(name, function callback(result) {
    this.assert.equal(result.value, '123456');
    this.assert.equals(result.name, 'test_cookie');
  });
}

getCookies since v0.4.0

Retrieve all cookies visible to the current page. The cookies are returned as an array of cookie JSON object, as defined here.

Uses cookie protocol command.

Arguments:
Name Type description
callback function The callback function which will receive the response as an argument.
Returns
Type description
Array.<object> A list of cookies.
Usage:

this.demoTest = function(browser) {
  browser.getCookies(function callback(result) {
    this.assert.equal(result.value.length, 1);
    this.assert.equals(result.value[0].name, 'test_cookie');
  });
}

getCssProperty

Retrieve the value of a css property for a given DOM element. Uses elementIdCssProperty protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
cssProperty string The CSS property to inspect.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
* The value of the css property
Usage:

this.demoTest = function (client) {
  client.getCssProperty("#main ul li a.first", "display", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value, 'inline');
  });
};

getElementSize

Determine an element's size in pixels. Uses elementIdSize protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
{width: number, height: number} The width and height of the element in pixels
Usage:

this.demoTest = function (client) {
  client.getElementSize("#main ul li a.first", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value.width, 500);
    this.assert.equal(result.value.height, 20);
 });
};

getLocation

Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page.

The element's coordinates are returned as a JSON object with x and y properties. Uses elementIdLocation protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
x:number, y:number The X and Y coordinates for the element on the page.
Usage:

this.demoTest = function (client) {
  client.getLocation("#main ul li a.first", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value.x, 200);
    this.assert.equal(result.value.y, 200);
  });
};

getLocationInView

Determine an element's location on the screen once it has been scrolled into view. Uses elementIdLocationInView protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
x: number, y: number The X and Y coordinates for the element on the page.
Usage:

this.demoTest = function (browser) {
  browser.getLocationInView("#main ul li a.first", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value.x, 200);
    this.assert.equal(result.value.y, 200);
  });
};

getLog

Gets a log from selenium

Arguments:
Name Type description
typeString string|function Log type to request
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function(client) {
  this.getLog('browser', function(logEntriesArray) {
    console.log('Log length: ' + logEntriesArray.length);
    logEntriesArray.forEach(function(log) {
       console.log('[' + log.level + '] ' + log.timestamp + ' : ' + log.message);
     });
  });
};

getLogTypes

Gets the available log types

this.demoTest = function(client) {
  this.getLogTypes(function(typesArray) {

  });
};
Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

getTagName

Query for an element's tag name. Uses elementIdName protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
number The element's tag name, as a lowercase string.
Usage:

this.demoTest = function (client) {
  client.getTagName("#main ul li .first", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value, "a");
  });
};

getText

Returns the visible text for the element. Uses elementIdText protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
string The element's visible text.
Usage:

this.demoTest = function (browser) {
  browser.getText("#main ul li a.first", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value, "nightwatchjs.org");
  });
};

getTitle

Returns the title of the current page. Uses title protocol command.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
string The page title.
Usage:

 this.demoTest = function (browser) {
   browser.getTitle(function(title) {
     this.assert.equal(typeof title, 'string');
     this.assert.equal(title, 'Nightwatch.js');
   });
 };

getValue

Returns a form element current value. Uses elementIdValue protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
string The element's value.
Usage:

this.demoTest = function (browser) {
  browser.getValue("form.login input[type=text]", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value, "enter username");
  });
};

init since v0.4.0

This command is an alias to url and also a convenience method when called without any arguments in the sense that it performs a call to .url() with passing the value of launch_url field from the settings file.
Uses url protocol command.

Arguments:
Name Type description
url
Optional
string Url to navigate to.
Usage:

this.demoTest = function (client) {
  client.init();
};

injectScript since v0.4.0

Utility command to load an external script into the page specified by url.

Arguments:
Name Type description
scriptUrl string The script file url
id
Optional
string Dom element id to be set on the script tag.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
HTMLScriptElement The newly created script tag.
Usage:

this.demoTest = function(client) {
  this.injectScript('<a href='http://example.org/js/utility.js'>http://example.org/js/utility.js</a>', function() {
    // we're all done here.
  });
};

isLogAvailable

Utility command to test if the log type is available

Arguments:
Name Type description
typeString string|function Type of log to test
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function(browser) {
  browser.isLogAvailable('browser', function(isAvailable) {
    // do something more in here
  });
}

isVisible

Determine if an element is currently displayed. Uses elementIdDisplayed protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (browser) {
  browser.isVisible('#main', function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value, true);
  });
};

maximizeWindow since v0.5.13

Maximizes the current window.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

 this.demoTest = function (browser) {
   browser.maximizeWindow();
 };

moveToElement

Move the mouse by an offset of the specified element. Uses moveTo protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
xoffset number X offset to move to, relative to the top-left corner of the element.
yoffset number Y offset to move to, relative to the top-left corner of the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (browser) {
  browser.moveToElement('#main', 10, 10);
};

pause

Suspends the test for the given time in milliseconds. If the milliseconds argument is missing it will suspend the test indefinitely

Arguments:
Name Type description
ms number The number of milliseconds to wait.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (browser) {
  browser.pause(1000);
  // or suspend indefinitely
  browser.pause();
};

perform

A simple perform command which allows access to the "api" in a callback.
Can be useful if you want to read variables set by other commands.

Arguments:
Name Type description
callback function the function to run as part of the queue; it is called with the <code>browser</code> object as the first argument and optionally a <code>done</code> callback in case of an async operation.
Usage:

this.demoTest = function (browser) {
  var elementValue;
  browser
    .getValue('.some-element', function(result) {
      elementValue = result.value;
    })
    // other stuff going on ...
    .perform(function(client, done) {
      console.log('elementValue', elementValue);
      // potentially other async stuff going on
      // on finished, call the done callback
      done();
    });
};

resizeWindow since v0.3.0

Resizes the current window.

Arguments:
Name Type description
width number The new window width.
width height The new window height.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

 this.demoTest = function (browser) {
   browser.resizeWindow(1000, 800);
 };

saveScreenshot

Take a screenshot of the current page and saves it as the given filename.

Arguments:
Name Type description
fileName string The complete path to the file name where the screenshot should be saved.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

 this.demoTest = function (browser) {
   browser.saveScreenshot('/path/to/fileName.png');
 };

setCookie since v0.4.0

Set a cookie, specified as a cookie JSON object, as defined here.

Uses cookie protocol command.

Arguments:
Name Type description
cookie object The cookie object.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function(browser) {
  browser.setCookie({
    name     : "test_cookie",
    value    : "test_value",
    path     : "/", (Optional)
    domain   : "example.org", (Optional)
    secure   : false, (Optional)
    httpOnly : false, // (Optional)
    expiry   : 1395002765 // (Optional) time in seconds since midnight, January 1, 1970 UTC
  });
}

setValue

See /session/:sessionId/element/:id/value

Sends some text to an element. Can be used to set the value of a form element or to send a sequence of key strokes to an element. Any UTF-8 character may be specified.

An object map with available keys and their respective UTF-8 characters, as defined on W3C WebDriver draft spec, is loaded onto the main Nightwatch instance as client.Keys.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
value string|array The text to send to the element or key strokes.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

// send some simple text to an input
this.demoTest = function (browser) {
  browser.setValue('input[type=text]', 'nightwatch');
};
//
// send some text to an input and hit enter.
this.demoTest = function (browser) {
  browser.setValue('input[type=text]', ['nightwatch', browser.Keys.ENTER]);
};

submitForm

Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element. Uses submit protocol command.

Arguments:
Name Type description
selector string The CSS/Xpath selector used to locate the element.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

this.demoTest = function (browser) {
  browser.submitForm('form.login');
};

switchWindow since v0.3.0

Change focus to another window. The window to change focus to may be specified by its server assigned window handle, or by the value of its name attribute.

To find out the window handle use window_handles protocol action

Arguments:
Name Type description
handleOrName string The server assigned window handle or the name attribute.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

 this.demoTest = function (browser) {
   browser.window_handles(function(result) {
     var handle = result.value[0];
     browser.switchWindow(handle);
   });
 };

urlHash since v0.4.0

Convenience method that adds the specified hash (i.e. url fragment) to the current value of the launch_url as set in nightwatch.json.

Arguments:
Name Type description
hash string The hash to add/replace to the current url (i.e. the value set in the launch_url property in nightwatch.json).
Usage:

this.demoTest = function (client) {
  client.urlHash('#hashvalue');
  // or
  client.urlHash('hashvalue');
};

waitForElementNotPresent since v0.4.0

Opposite of waitForElementPresent. Waits a given time in milliseconds for an element to be not present (i.e. removed) in the page before performing any other commands or assertions.

If the element is still present after the specified amount of time, the test fails.

You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file.

Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).

Arguments:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails.
callback
Optional
function Optional callback function to be called when the command finishes.
message
Optional
string Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms).
Usage:

this.demoTest = function (browser) {
  browser.waitForElementNotPresent('#dialog', 1000);
};

waitForElementNotVisible since v0.4.0

Opposite of waitForElementVisible. Waits a given time in milliseconds for an element to be not visible (i.e. hidden but existing) in the page before performing any other commands or assertions.

If the element fails to be hidden in the specified amount of time, the test fails.

You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file.

Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).

Arguments:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails.
callback
Optional
function Optional callback function to be called when the command finishes.
message
Optional
string Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms).
Usage:

this.demoTest = function (browser) {
  browser.waitForElementNotVisible('#dialog', 1000);
};

waitForElementPresent

Waits a given time in milliseconds for an element to be present in the page before performing any other commands or assertions.

If the element fails to be present in the specified amount of time, the test fails. You can change this by setting abortOnFailure to false.

You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file.

Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).

Arguments:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails.
callback
Optional
function Optional callback function to be called when the command finishes.
message
Optional
string Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms).
Usage:

this.demoTest = function (browser) {
  browser.waitForElementPresent('body', 1000);
  // continue if failed
  browser.waitForElementPresent('body', 1000, false);
  // with callback
  browser.waitForElementPresent('body', 1000, function() {
    // do something while we're here
  });
  // custom Spanish message
  browser.waitForElementPresent('body', 1000, 'elemento %s no era presente en %d ms');
  // many combinations possible - the message is always the last argument
  browser.waitForElementPresent('body', 1000, false, function() {}, 'elemento %s no era presente en %d ms');
};

waitForElementVisible

Waits a given time in milliseconds for an element to be visible in the page before performing any other commands or assertions.

If the element fails to be present and visible in the specified amount of time, the test fails. You can change this by setting abortOnFailure to false.

You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file.

Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).

Arguments:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails.
callback
Optional
function Optional callback function to be called when the command finishes.
message
Optional
string Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms).
Usage:

this.demoTest = function (browser) {
  browser.waitForElementVisible('body', 1000);
  // continue if failed
  browser.waitForElementVisible('body', 1000, false);
  // with callback
  browser.waitForElementVisible('body', 1000, function() {
    // do something while we're here
  });
  // custom Spanish message
  browser.waitForElementVisible('body', 1000, 'elemento %s no era visible en %d ms');
  // many combinations possible - the message is always the last argument
  browser.waitForElementVisible('body', 1000, false, function() {}, 'elemento %s no era visible en %d ms');
};

The protocol commands are most of the times simple mappings to the Selenium JsonWireProtocol endpoints.

Some of them are basic commands (such as url and execute) and others are internal commands being used by Nightwatch commands and assertions.

Implementation of the Selenium commands is incomplete however and still a work in progress.

acceptAlert

See /session/:sessionId/accept_alert

Accepts the currently displayed alert dialog. Usually, this is equivalent to clicking on the 'OK' button in the dialog.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

back

See /session/:sessionId/back

Navigate backwards in the browser history, if possible.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

See /session/:sessionId/cookie

Retrieve or delete all cookies visible to the current page or set a cookie.

Arguments:
Name Type description
method string Http method
callbackOrCookie
Optional
function|object Optional callback function to be called when the command finishes.

dismissAlert

See /session/:sessionId/dismiss_alert

Dismisses the currently displayed alert dialog. For confirm() and prompt() dialogs, this is equivalent to clicking the 'Cancel' button.

For alert() dialogs, this is equivalent to clicking the 'OK' button.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

doubleClick

Double-clicks at the current mouse coordinates (set by moveto).

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

element

See /session/:sessionId/element

Search for an element on the page, starting from the document root. The located element will be returned as a WebElement JSON object.

Arguments:
Name Type description
using string The locator strategy to use.
value string The search target.
callback
Optional
function Optional callback function to be called when the command finishes.

elementActive

See /session/:sessionId/element/active

Get the element on the page that currently has focus.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdAttribute

See /session/:sessionId/element/:id/attribute/:name

Get the value of an element's attribute.

Arguments:
Name Type description
id string ID of the element to route the command to.
attributeName string The attribute name
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdClear

See /session/:sessionId/element/:id/clear

Clear a TEXTAREA or text INPUT element's value.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdClick

See /session/:sessionId/element/:id/click

Click on an element.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdCssProperty

See /session/:sessionId/element/:id/css/:propertyName

Query the value of an element's computed CSS property.

The CSS property to query should be specified using the CSS property name, not the JavaScript property name (e.g. background-color instead of backgroundColor).

Arguments:
Name Type description
id string ID of the element to route the command to.
cssPropertyName string
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdDisplayed

See /session/:sessionId/element/:id/displayed

Determine if an element is currently displayed.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdElement

See /session/:sessionId/element/:id/element

Search for an element on the page, starting from the identified element. The located element will be returned as a WebElement JSON object.

Arguments:
Name Type description
id string ID of the element to route the command to.
using string The locator strategy to use.
value string The search target.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdElements

See /session/:sessionId/element/:id/elements

Search for multiple elements on the page, starting from the identified element. The located element will be returned as a WebElement JSON objects.

Arguments:
Name Type description
id string ID of the element to route the command to.
using string The locator strategy to use.
value string The search target.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdEnabled

See /session/:sessionId/element/:id/enabled

Determine if an element is currently enabled.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdEquals

See /session/:sessionId/element/:id/equals/:other

Test if two element IDs refer to the same DOM element.

Arguments:
Name Type description
id string ID of the element to route the command to.
otherId string ID of the element to compare against.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdLocation

See /session/:sessionId/element/:id/location

Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page.

The element's coordinates are returned as a JSON object with x and y properties.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
x:number, y:number The X and Y coordinates for the element on the page.

elementIdLocationInView

See /session/:sessionId/element/:id/location_in_view

Determine an element's location on the screen once it has been scrolled into view.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdName

See /session/:sessionId/element/:id/name

Query for an element's tag name.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdSelected

See /session/:sessionId/element/:id/selected

Determine if an OPTION element, or an INPUT element of type checkbox or radio button is currently selected.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdSize

See /session/:sessionId/element/:id/size

Determine an element's size in pixels. The size will be returned as a JSON object with width and height properties.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdText

See /session/:sessionId/element/:id/text

Returns the visible text for the element.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

elementIdValue

See /session/:sessionId/element/:id/value

Send a sequence of key strokes to an element or returns the current value of the element.

Arguments:
Name Type description
id string ID of the element to route the command to.
value
Optional
string|array|none Value to send to element in case of a POST
callback
Optional
function Optional callback function to be called when the command finishes.

elements

See /session/:sessionId/elements

Search for multiple elements on the page, starting from the document root. The located elements will be returned as a WebElement JSON objects.
Valid strings to use as locator strategies are: "class name", "css selector", "id", "name", "link text", "partial link text", "tag name", "xpath"

Arguments:
Name Type description
using string The locator strategy to use.
value string The search target.
callback function Callback function to be invoked with the result when the command finishes.

execute

See /session/:sessionId/execute

Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client.
The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client.

The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified.

Arguments:
Name Type description
body string|function The function body to be injected.
args Array An array of arguments which will be passed to the function.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
* The script result.
Usage:

 this.demoTest = function (browser) {
   browser.execute(function(data) {
     // resize operation
     return true;
   }, [imagedata], function(result) {
     ...
   });
 };

executeAsync

See /session/:sessionId/execute_async

Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous and the result of evaluating the script is returned to the client.

Asynchronous script commands may not span page loads. If an unload event is fired while waiting for a script result, an error should be returned to the client.

Arguments:
Name Type description
script string|function The function body to be injected.
args Array An array of arguments which will be passed to the function.
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
* The script result.
Usage:

 this.demoTest = function (browser) {
   browser.executeAsync(function(data, done) {
     someAsyncOperation(function() {
       done(true);
     });
   }, [imagedata], function(result) {
     // ...
   });
 };

forward

See /session/:sessionId/back

Navigate forwards in the browser history, if possible.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

frame

See /session/:sessionId/frame

Change focus to another frame on the page. If the frame id is missing or null, the server should switch to the page's default content.

Arguments:
Name Type description
frameId
Optional
string|number|null Identifier for the frame to change focus to.
callback
Optional
function Optional callback function to be called when the command finishes.

frameParent since v0.4.8

See /session/:sessionId/frame/parent

Change focus to the parent context. If the current context is the top level browsing context, the context remains unchanged.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

getAlertText

See /session/:sessionId/alert_text

Gets the text of the currently displayed JavaScript alert(), confirm(), or prompt() dialog.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
string The text of the currently displayed alert.

keys

See /session/:sessionId/keys

Send a sequence of key strokes to the active element. The sequence is defined in the same format as the sendKeys command.
An object map with available keys and their respective UTF-8 characters, as defined on W3C WebDriver draft spec, is loaded onto the main Nightwatch instance as client.Keys.

Rather than the setValue, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed.

Arguments:
Name Type description
keysToSend Array The keys sequence to be sent.
callback
Optional
function Optional callback function to be called when the command finishes.

mouseButtonClick

See /session/:sessionId/click

Click at the current mouse coordinates (set by moveto).

The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly.

Arguments:
Name Type description
button string|number The mouse button
callback
Optional
function Optional callback function to be called when the command finishes.

mouseButtonDown

See /session/:sessionId/buttondown

Click and hold the left mouse button (at the coordinates set by the last moveto command). Note that the next mouse-related command that should follow is mouseButtonUp . Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour.

Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly.

Arguments:
Name Type description
button string|number The mouse button
callback
Optional
function Optional callback function to be called when the command finishes.

mouseButtonUp

See /session/:sessionId/buttonup

Releases the mouse button previously held (where the mouse is currently at). Must be called once for every mouseButtonDown command issued.

Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly.

Arguments:
Name Type description
button string|number The mouse button
callback
Optional
function Optional callback function to be called when the command finishes.

moveTo

See /session/:sessionId/moveto

Move the mouse by an offset of the specificed element. If no element is specified, the move is relative to the current mouse cursor. If an element is provided but no offset, the mouse will be moved to the center of the element.

If the element is not visible, it will be scrolled into view.

Arguments:
Name Type description
element string Opaque ID assigned to the element to move to. If not specified or is null, the offset is relative to current position of the mouse.
xoffset number X offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
yoffset number Y offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element.
callback
Optional
function Optional callback function to be called when the command finishes.

refresh

See /session/:sessionId/refresh

Refresh the current page.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

screenshot

See /session/:sessionId/screenshot

Take a screenshot of the current page.

Arguments:
Name Type description
log_screenshot_data boolean Whether or not the screenshot data should appear in the logs when running with --verbose
callback
Optional
function Optional callback function to be called when the command finishes.

session

See /session

Get info about, delete the current session or create a new session.

Arguments:
Name Type description
action
Optional
string The http verb to use, can be "get", "post" or "delete". If only the callback is passed, get is assumed as default.
callback
Optional
function Optional callback function to be called when the command finishes.

sessionLog

See /session/:sessionId/log

Gets the text of the log type specified

Arguments:
Name Type description
typeString string Type of log to request
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
Array Array of the text entries of the log.

sessionLogTypes

See /session/:sessionId/log/types

Gets an array of strings for which log types are available.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.
Returns
Type description
Array Available log types

sessions

See /sessions

Returns a list of the currently active sessions.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

setAlertText

See /session/:sessionId/alert_text

Sends keystrokes to a JavaScript prompt() dialog.

Arguments:
Name Type description
value string Keystrokes to send to the prompt() dialog
callback
Optional
function Optional callback function to be called when the command finishes.

source

See /session/:sessionId/source

Get the current page source.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

status

See /status

Query the server's current status.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

submit

See /session/:sessionId/element/:id/submit

Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element.

Arguments:
Name Type description
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

timeouts

See /session/:sessionId/timeouts

Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client.

Arguments:
Name Type description
type string The type of operation to set the timeout for. Valid values are: "script" for script timeouts, "implicit" for modifying the implicit wait timeout and "page load" for setting a page load timeout.
ms number The amount of time, in milliseconds, that time-limited commands are permitted to run.
callback
Optional
function Optional callback function to be called when the command finishes.

timeoutsAsyncScript

See /session/:sessionId/timeouts/async_script

Set the amount of time, in milliseconds, that asynchronous scripts executed by /session/:sessionId/execute_async are permitted to run before they are aborted and a |Timeout| error is returned to the client.

Arguments:
Name Type description
ms number The amount of time, in milliseconds, that time-limited commands are permitted to run.
callback
Optional
function Optional callback function to be called when the command finishes.

timeoutsImplicitWait

See /session/:sessionId/timeouts/implicit_wait

Set the amount of time the driver should wait when searching for elements. If this command is never sent, the driver will default to an implicit wait of 0ms.

Arguments:
Name Type description
ms number The amount of time, in milliseconds, that time-limited commands are permitted to run.
callback
Optional
function Optional callback function to be called when the command finishes.

title

See /session/:sessionId/title

Get the current page title.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

url

See /session/:sessionId/url

Retrieve the URL of the current page or navigate to a new URL.

Arguments:
Name Type description
url
Optional
string|function If missing, it will return the URL of the current page as an argument to the supplied callback
callback
Optional
Function

window since v0.3.0

See /session/:sessionId/window

Change focus to another window or close the current window.

Arguments:
Name Type description
method string The HTTP method to use
handleOrName string The window to change focus to.
callback
Optional
function Optional callback function to be called when the command finishes.

windowHandle

See /session/:sessionId/window_handle

Retrieve the current window handle.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

windowHandles

See /session/:sessionId/window_handles

Retrieve the list of all window handles available to the session.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

windowMaximize

See /session/:sessionId/window/:windowHandle/maximize

Retrieve the current window handle.

Arguments:
Name Type description
callback
Optional
function Optional callback function to be called when the command finishes.

windowSize

See /session/:sessionId/window/:windowHandle/size

Change or get the size of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window size.

Arguments:
Name Type description
windowHandle string
width number
height number
callback
Optional
function Optional callback function to be called when the command finishes.

Contact

Issues

Please report any issues or feature requests at github.com/nightwatchjs/nightwatch/issues

Questions/Getting Help

You're encouraged to ask any questions you might have regarding the usage of Nightwatch or its API on the Mailing List or on Twitter. In addition, there is a StackOverflow Nightwatch.js tag at your disposal.

Contributing

Any contribution would be most welcome, so feel free to fork and send me your pull requests.