What is Nightwatch?

Nightwatch.js is an automated end-to-end testing framework for web applications and websites. It is written in Node.js and uses the W3C WebDriver API (formerly Selenium WebDriver) for interacting with various browsers.

It is a complete testing solution which aims to simplify writing tests and setting up Continuous Integration and Continuous Delivery. Nightwatch can also be used for writing Node.js unit and integration tests. Read more about how Nightwatch was created here.

Nightwatch was created in Amsterdam, The Netherlands, and the name was inspired by the famous painting The Night Watch by Dutch 17th century artist Rembrandt van Rijn. The masterpiece is prominently displayed in the Rijksmuseum, in Amsterdam.

Overview of WebDriver

WebDriver is a general purpose library for automating web browsers. It was started as part of the Selenium project, which is a popular and comprehensive set of tools for browser automation, initially written for Java but now with support for most programming languages.

Nightwatch uses the WebDriver API to perform the browser automation related tasks, like opening windows or clicking links.

WebDriver is now a W3C specification aiming to standardise browser automation, providing a platform and a restful HTTP api as a way for web browsers to be remotely controlled.

Theory of Operation

Nightwatch works by interacting with a WebDriver-compatible HTTP server (such as ChromeDriver for Chrome or GeckoDriver for Firefox). The HTTP protocol is defined by the W3C WebDriver spec, which is derived from JSON Wire protocol.

All major browsers have a specific WebDriver implementation, called a driver, which Nightwatch uses behind the scenes to communicate with the browser. See the Install Webdriver section for details on the particular browser drivers.

Most of the times, Nightwatch needs to send at least 2 requests to the WebDriver server in order to perform a command or assertion, 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. See below for an example workflow for browser initialisation.

Theory of Operation

Nightwatch & Selenium Server

The communication can also be facilitated by the Selenium Server (also known as Selenium Grid) or a compatible cloud-based testing platform (like Browserstack, SauceLabs or CrossBrowserTesting).

Selenium Server Operation

Nightwatch is sometimes incorrectly described as a "Selenium binding" library. While it's true that Nightwatch can be (and is often) used together with the Selenium Server it's important to remember that Nightwatch is a complete testing solution which contains a built-in CLI test runner, an extendible command and assertion library, and support for page object model.

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
  • add -g option to make nightwatch runner available globally in your system.
  • add --save-dev option to save nightwatch as a devDependency in your package.json.

Install WebDriver

Depending on your target browser, you will need a specific WebDriver package. Below there are the most popular ones that you can install from NPM or download and configure separately.

Since version 1.3, a configuration file nightwatch.conf.js is generated automatically if no config file is found in the current folder. The file contains all the necessary settings for the available browser drivers, including setup for running with Selenium Server.
WebDriver Binary Browser Description
GeckoDriver Mozilla Firefox Standalone server which implements the W3C WebDriver protocol to communicate with Gecko browsers, such as Firefox.
ChromeDriver Google Chrome Standalone server which implements the JSON Wire Protocol for Chromium, however it is currently in the process of transitioning to the W3C WebDriver spec.

Available for Chrome on Android and Chrome on Desktop (Mac, Linux, Windows and ChromeOS).
Microsoft WebDriver Microsoft Edge Windows executable which supports both the W3C WebDriver spec and JSON Wire Protocol for running tests against Microsoft Edge.
SafariDriver Microsoft Edge The /usr/bin/safaridriver binary comes pre-installed with recent versions of Mac OS and it's available to use following the instructions on Apple Developer website.

More information is available on About WebDriver for Safari page.

Installing the WebDriver services can be done either by downloading the binary directly or by using an NPM package.

GeckoDriver

GeckoDriver can be simply installed from NPM and no further configuration is necessary.

npm install geckodriver --save-dev

Alternatively, it can be downloaded from the GeckoDriver Releases page on GitHub. Release notes are also available there.

ChromeDriver

Same as GeckoDriver, ChromeDriver can be simply installed from NPM and no further configuration is necessary.

Alternatively, it can be downloaded from the ChromeDriver Downloads page.

npm install chromedriver --save-dev

Microsoft WebDriver

WebDriver for Microsoft Edge is now a Windows Feature on Demand. To install run the following in an elevated command prompt:

DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0

More details about installation and usage documentation are available on the official Microsoft WebDriver homepage.

SafariDriver

The safaridriver binary is already installed on recent versions of Mac OS, however some manual configuration is needed before tests can be run against Safari.

You will need to run the following once, before using the safaridriver:

safaridriver --enable

More details are available on the Apple Developer website.

Install Selenium Server

Using Selenium Standalone Server used to be the de-facto standard for managing the various browser drivers and services, but starting with Nightwatch 1.0 is no longer required, nor is it recommended for testing against a single browser.

You will only need Selenium Server when testing against Internet Explorer, if you wish to run tests in parallel in multiple browsers, or in a Selenium Grid environment.

Download Java

Selenium Server is a Java application, which means you will also need to have the Java Development Kit (JDK) installed, minimum required version is 7. You can check this by running java -version from the command line.

Install From NPM

The easiest way to install the Selenium Server is from NPM. Nightwatch automatic configuration is already prepared for usage with this package against Chrome, Firefox, and Internet Explorer.

npm install selenium-server --save-dev

Download Selenium

You can find the latest Selenium Server stable and alpha version on the Selenium downloads page.

Download the selenium-server-standalone-{VERSION}.jar file 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

Using Selenium Standalone Server

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

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

Starting with Selenium 3, FirefoxDriver is no longer included in the package. Also, starting with version 48, Firefox is no longer compatible with FirefoxDriver which is shipped with Selenium 2.x. Firefox users are advised to use GeckoDriver for their testing. For more info, refer to the browser setup section.

More info about running the Selenium Server can be found here: https://selenium.dev/documentation/en/remote_webdriver/remote_webdriver_server

It is likely you will run your tests against multiple environments and/or different browsers. Nightwatch provides a concept for defining different environments, in which you can set specific test settings.

The environments are located under the "test_settings" dictionary in the configuration file. A default environment is always required from which the other environments inherit the settings. You can overwrite any test setting for each environment as needed.

The configuration file which is auto-generated by Nightwatch (nightwatch.conf.js) contains several pre-defined test environments for running tests against several different browsers (Firefox, Chrome, Safari), and also for running tests using Selenium Server or popular cloud testing provider Browserstack.com.

Here’s an extract:

module.exports = {
  src_folders: [],

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

    safari: {
      desiredCapabilities : {
        browserName : 'safari',
        alwaysMatch: {
          acceptInsecureCerts: false
        }
      },
      webdriver: {
        port: 4445,
        start_process: true,
        server_path: '/usr/bin/safaridriver'
      }
    },

    firefox: {
      desiredCapabilities : {
        browserName : 'firefox'
      },

      webdriver: {
        start_process: true,
        port: 4444,
        server_path: require('geckodriver').path
      }
    }
  }
}

Considering this setup, to run tests, for instance, against Safari, we would run the following the command-line:

nightwatch --env safari

Refer to the Running Tests documentation section to learn more about how to user the Nightwatch test runner.

Extending Test Environments

In some cases, you will need to extend another environment which is not the default one. A common scenario for this use case is the situation when you are using the Selenium Server or a cloud-based testing service (such as Sauce Labs or Browserstack).

In this case you will need most likely need a base environment for common settings (such as host or port) and several sub-environments for each target browser (e.g. Firefox, Chrome).

Going back to the auto-generated configuration file, nightwatch.conf.js, we have provided an example structure for using the Selenium Server with Chrome and Firefox.

Here's the relevant extract. Notice the "extends" property:

module.exports = {
  src_folders: [],

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

    selenium: {
      // Selenium Server is running locally and is managed by Nightwatch
      selenium: {
        start_process: true,
        port: 4444,
        server_path: require('selenium-server').path,
        cli_args: {
          'webdriver.gecko.driver': require('geckodriver').path,
          'webdriver.chrome.driver': require('chromedriver').path
        }
      },
      webdriver: {
        start_process: false
      }
    },

    'selenium.chrome': {
      extends: 'selenium',
      desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions : {
          w3c: false
        }
      }
    },

    'selenium.firefox': {
      extends: 'selenium',
      desiredCapabilities: {
        browserName: 'firefox'
      }
    }
  }
}

With this setup, you can run the tests using Selenium Server and Firefox with this command:

nightwatch --env selenium.firefox

Another useful concept that Nightwatch provides is test globals. In its most simple form, it is a dictionary of name-value pairs which is defined in your configuration file.

Globals can be defined either as a "globals" property or as an external file which is specified as the "globals_path" property.

Here's an example definition using the "globals" property in nightwatch.json:

{
  "src_folders": [],

  "test_settings": {
    "default": {
      "launch_url": "https://nightwatchjs.org",

      "globals": {
        "myGlobalVar" : "some value",
        "otherGlobal" : "some other value"
      }
    }
  }
}

Like the launch_url property, the globals object is made available directly on the Nightwatch api which is passed to the tests.

module.exports = {
  'Demo test' : function (browser) {

    console.log(browser.globals.myGlobalVar); // myGlobalVar == "some value"
  }
};

Pre-defined Globals

The following global properties can used to control the behaviour of the test runner and are defined with the following default values:

module.exports = {
  globals: {
    // this controls whether to abort the test execution when an assertion failed and skip the rest
    // it's being used in waitFor commands and expect assertions
    abortOnAssertionFailure: true,

    // this will overwrite the default polling interval (currently 500ms) for waitFor commands
    // and expect assertions that use retry
    waitForConditionPollInterval: 500,

    // default timeout value in milliseconds for waitFor commands and implicit waitFor value for
    // expect assertions
    waitForConditionTimeout : 5000,

    // this will cause waitFor commands on elements to throw an error if multiple
    // elements are found using the given locate strategy and selector
    throwOnMultipleElementsReturned: false,

    // By default a warning is printed if multiple elements are found using the given locate strategy
    // and selector; set this to true to suppress those warnings
    suppressWarningsOnMultipleElementsReturned: false,

    // controls the timeout value for async hooks. Expects the done() callback to be invoked within this time
    // or an error is thrown
    asyncHookTimeout : 10000,

    // controls the timeout value for when running async unit tests. Expects the done() callback to be invoked within this time
    // or an error is thrown
    unitTestsTimeout : 2000,

    // controls the timeout value for when executing the global async reporter. Expects the done() callback to be 
    // invoked within this time or an error is thrown
    customReporterCallbackTimeout: 20000,

    // 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.
    retryAssertionTimeout: 5000,

    // Custom reporter
    reporter: function(results, done) {
      // do something with the results
      done(results);
    }
  }
}

Environment Specific Globals

Like other test settings, globals have the ability to be overwritten per test environment. Consider this configuration:

{
  "src_folders": [],

  "test_settings": {
    "default": {
      "launch_url": "https://nightwatchjs.org",

      "globals": {
        "myGlobalVar" : "some value",
        "otherGlobal" : "some other value"
      }
    },

    "integration": {
      "globals": {
        "myGlobalVar" : "integrated global"
      }
} } }

If we still pass the --env integration option to the runner, then our globals object will look like below:

nightwatch --env integration
module.exports = {
  'Demo test' : function (browser) {

    console.log(browser.globals.myGlobalVar); // myGlobalVar == "integrated global"
  }
};

External Test Globals

Test globals can also be defined in an external file, specified by the "globals_path" settings in your configuration file.

The external globals file can also contain global test hooks, a custom reporter and other test specific settings. Refer to the External Globals section for more details.

nightwatch.json

The nightwatch test runner binary expects a configuration file, using by default a nightwatch.json file from the current working directory. A nightwatch.conf.js file will also be loaded by default, if found.

At this point you should have at least one WebDriver package installed in your project. Refer to the WebDriver installation section for details.

Auto-generated Configuration

Since version 1.3, Nightwatch will generate a nightwatch.conf.js config file by default, based on the operation system and existing driver packages. If a nightwatch.json or nightwatch.conf.js file is found in the current folder, nothing happens and the file is not generated.

So far, we have included support for Chrome, Firefox, Safari, and Internet Explorer. The following packages can be used from NPM and, if installed, Nightwatch will automatically detect and configure the test runner:

Manual Configuration

Create the nightwatch.json in the project's root folder.

Assuming you have downloaded or installed the ChromeDriver service, the simplest nightwatch.json file will look like this, where node_modules/.bin/chromedriver is the path where ChromeDriver is installed:

{
  "src_folders" : ["tests"],

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

  "test_settings" : {
    "default" : {
      "desiredCapabilities": {
        "browserName": "chrome"
      }
    }
  }
}

nightwatch.conf.js

Using a .js configuration files is also possible, with nightwatch.conf.js always taking precedence if both files are found. A .js file is often more desirable as it provides more capabilities which come useful in large projects that need to test on several browsers.

Here's an example config file which uses Firefox as target browser.

module.exports = {
  // An array of folders (excluding subfolders) where your tests are located;
  // if this is not specified, the test source must be passed as the second argument to the test runner.
  src_folders: [],

  webdriver: {
    start_process: true,
    port: 4444,
    server_path: require('geckodriver').path,
    cli_args: [
      // very verbose geckodriver logs
      // '-vv'
    ]
  },

  test_settings: {
    default: {
      launch_url: 'https://nightwatchjs.org',
      desiredCapabilities : {
        browserName : 'firefox',
        alwaysMatch: {
          // Enable this if you encounter unexpected SSL certificate errors in Firefox
          // acceptInsecureCerts: true,
          'moz:firefoxOptions': {
            args: [
              // '-headless',
              // '-verbose'
            ],
          }
        }
      }
    }
  }
};

Base Settings Suggest edits

Below are the default settings that will be passed to the Nightwatch instance during test execution.

Name type default description
test_settings object An object in which all the test environments are defined, each overwriting test settings as needed. A default environment is always required, from which the other environments inherit settings from. See Defining Test Environments below for details.
webdriver object An object containing WebDriver related configuration options.
src_folders Optional string|array none An array of folders (excluding subfolders) where the tests are located.

If this is not specified, the test source must be passed inline as the second argument to the test runner.
selenium Optional object An object containing Selenium Server related configuration options. If Selenium is not used, webdriver options should be set instead.
Starting with Nightwatch 1.0, Selenium is only required when testing against a Grid setup or a cloud testing service (such as SauceLabs or BrowserStack).
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
string|array none Location(s) where page object files will be loaded from.
globals_path
Optional
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.

Test Runner Settings

The below settings are used to control the way the built-in CLI test runner works.

Name type default description
test_runner
Optional
string|object "default" Specifies which test runner to use when running the tests. Values can be either default (built-in nightwatch runner) or mocha.


Example: "test_runner" : {"type" : "mocha", "options" : {"ui" : "tdd"}}
parallel_process_delay
Optional
integer 10 Specifies the delay(in milliseconds) between starting the child processes when running in parallel mode.
test_workers
Optional
boolean|object false Whether or not to run individual test suites in parallel using a test worker for each. 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"}
unit_tests_mode
Optional
boolean false Controls whether to run tests in unit testing mode, which means the session will not automatically be created.

Test Session Settings

These settings are used to fine tune the behaviour of a test session and define properties which may be available during the course of it.

The launch_url property

This property will be made available to the main Nightwatch api which is used in the tests. Its value depends on which environment is used. More on test environments under the Nightwatch Runner section.

If you run your tests specifying the integration environment (with --env integration) the launch_url will be set to http://staging.host, as per the configuration. Otherwise it will have the value defined in the default environment (i.e. http://localhost).

module.exports = {
  'Demo test' : function (browser) {
    browser
      .url(browser.launchUrl)
      // ...
      .end();
  }
};
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.
start_session boolean true Whether or not to automatically start the WebDriver session. This will typically be set to false when running unit/integration tests that don't interact with the Webdriver server.
desiredCapabilities object The WebDriver capabilities when a new session will be created. You can specify browser name for instance along with other capabilities.
Example:

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

You can view the complete list of capabilities here.
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" : ""
}
globals object An object which will be made available within the test and can be overwritten per environment. Example:

"globals" : {
  "myGlobal" : "some_global"
}
Globals can also be defined in an external file. More on External Globals.
persist_globals boolean false Set this to true if you'd like to persist the same globals object between testsuite runs or have a (deep) copy of it per each testsuite.
end_session_on_fail boolean true End the session automatically when the test is being terminated, usually after a failed assertion.
skip_testcases_on_fail boolean true Skip the remaining testcases (or test steps) from the same test suite (i.e. test file), when one testcase fails.
use_xpath boolean false Use xpath as the default locator strategy
sync_test_names
boolean true A name property will be added to the desiredCapabilities containing the test suite name when this is enabled. It is useful when using cloud testing services.
persist_globals boolean false Set this to true if you'd like to persist the same globals object between testsuite runs or have a (deep) copy of it per each testsuite.
selenium_host
Deprecated - use selenium.host
string localhost The hostname/IP on which the Selenium Server is accepting connections.
selenium_port
Deprecated - use selenium.port
integer 4444 The port number on which the Selenium Server is accepting connections.

Filtering Settings

The below settings can be used to define ways of filtering test files.



Name type default description
exclude 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 string Folder or file pattern to be used when loading the tests. Files that don't match this pattern will be ignored.
Example:

"filter" : "tests/*-smoke.js"
skipgroup
string Skip a group of tests (a subfolder); can be a list of comma-separated values (no space).
skiptags
string Skip tests by tag name; can be a list of comma-separated values (no space)

Output Settings

The below settings can be used to control the output and logging when running tests.


Name type default description
output_folder string tests_output The location where the JUnit XML report files will be saved.
disable_colors boolean false Controls whether or not to disable coloring of the CLI output globally.
live_output boolean false This option is only useful when running tests in parallel. Controls whether or not to buffer the output.
silent boolean true Whether to show the extended HTTP traffic command logs from the WebDriver or Selenium server.
output boolean true Used to disable CLI output completely.
detailed_output boolean true By default detailed assertion output is displayed while the test is running. Set this to false if you'd like to only see the test case name displayed and pass/fail status. Detailed output is disabled by default when running tests in parallel.
disable_error_log boolean false Set this to true if you'd like to not display errors during the execution of the test (they are shown at the end always).
log_screenshot_data boolean false Used to enable showing the Base64 image data in the (verbose) log when taking screenshots.

Below are a number of options for the Webdriver service. Nightwatch can start and stop the Webdriver 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 binary file inside server_path.

Name type default description
start_process boolean false When this is enabled, the Webdriver server is run in background in a child process and started/stopped automatically.
Nightwatch includes support for managing Chromedriver, Geckodriver (Firefox), Safaridriver, and Selenium Server. Please refer to the Install Webdriver section for details.
server_path string none Only useful if start_process is enabled.
host string Only needed when the Webdriver service is running on a different machine.
port integer The port number on which the Webdriver service will listen and/or on which Nightwatch will attempt to connect.
log_path Optional string|boolean none The location where the Webdriver service log file output.log file will be placed. Defaults to current directory.
To disable Webdriver logging, set this to false
cli_args Optional object none List of cli arguments to be passed to the Webdriver process. This varies for each Webdriver implementation.
keep_alive Optional boolean|object false Enable HTTP Keep-Alive. If set to true the keepAlive option is enabled with default settings (keepAliveMsecs = 3000).
If set to an object, can specify specify the keepAliveMsecs value.

Example: "keep_alive" : {"enabled" : true, "keepAliveMsecs" : 2000}
request_timeout_options Optional object timeout: 60000
retry_attempts: 0
Requests to the Webdriver service will timeout in timeout ms; A retry will happen retry_attempts number of times.

Example:

{timeout: 15000, retry_attempts: 5}
status_poll_interval
since v1.2.2
integer 100 Interval (in ms) to use between status ping checks when checking if the Webdriver server is up and running
max_status_poll_tries
since v1.2.2
integer 5 Maximum number of ping status check attempts when checking if the Webdriver server is up and running before returning a timeout error.
process_create_timeout
since v1.2.2
integer 120000 The entire time (in ms) to wait for the Node.js process to be created and running (default is 2 min), including spawning the child process and checking the status
username Optional string none Usually only needed for cloud testing Selenium services. In case the 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 Optional 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}"
proxy Optional string none Proxy requests to the Webdriver (or Selenium) service. http, https, socks(v5), socks5, sock4, and pac are accepted. Uses node-proxy-agent.

Example: http://user:pass@host:port
default_path_prefix Optional string Needed sometimes when using a Selenium Server. The prefix to be added to to all requests (e.g. /wd/hub).
use_legacy_jsonwire Optional boolean false Some Webdriver implementations (Safari, Edge) support both the W3C Webdriver API as well as the legacy JSON Wire (Selenium) API.

If the Selenium Server is used, then the connection related settings should be placed under the "selenium"". If both webdriver and selenium dictionaries are present, the selenium options will be merged with the webdriver ones.

The "selenium" settings should also be used when configuring connections to cloud-based testing providers, such as Browserstack, SauceLabs or CrossBrowserTesting.

Name type default description
start_process boolean false Whether or not to manage the Selenium process automatically.
server_path string none The location of the Selenium jar file. This needs to be specified if start_process is enabled.
E.g.: bin/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
version2 boolean false Set this to true if you need to use legacy Selenium Server 2.
port integer 4444 The port number Selenium will listen on and/or Nighwatch will attempt to connect to.
cli_args 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 by 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 works with Internet Explorer also. To enable this you have to download the IE Driver binary and specify it's location here.

    Alternatively you can install the package iedriver from NPM.

    Also you need to specify "internet explorer" as the browser name in the desiredCapabilities object.

Selenium Example Configuration

Here's an example configuration as part of the nightwatch.conf.js which uses a local Selenium Server with support for Firefox, Chrome, and Internet Explorer.

The following NPM packages are assumed to be installed in the current project:

module.exports = {
  src_folders: [],

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

    selenium: {
      // Selenium Server is running locally and is managed by Nightwatch
      selenium: {
        start_process: true,
        port: 4444,
        server_path: require('selenium-server').path,
        cli_args: {
          'webdriver.gecko.driver': require('geckodriver').path,
          'webdriver.chrome.driver': require('chromedriver').path,
          'webdriver.ie.driver': process.platform === 'win32' ? require('iedriver').path : ''
        }
      },
      webdriver: {
        start_process: false
      }
    },

    'selenium.chrome': {
      extends: 'selenium',
      desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions : {
          w3c: false
        }
      }
    },

    'selenium.firefox': {
      extends: 'selenium',
      desiredCapabilities: {
        browserName: 'firefox'
      }
    },

    'selenium.ie': {
      extends: 'selenium',
      desiredCapabilities: {
        browserName: 'internet explorer'
      }
    }
  }
}

Browserstack Example Configuration

Browserstack is one of the most popular cloud testing platforms. Using it with Nightwatch is very straightforward and there is configuration in the auto-generated nightwatch.conf.js file.

Once you have an account, you need to set the following environment variables. Dotenv files are also supported by Nightwatch.

  • BROWSERSTACK_USER
  • BROWSERSTACK_KEY

Remember to also enable HTTP keepalive for improved network performance.

module.exports = {
  src_folders: [],

  webdriver: {
    keep_alive: true
  }

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

    browserstack: {
      selenium: {
        host: 'hub-cloud.browserstack.com',
        port: 443
      },

      // More info on configuring capabilities can be found on:
      // https://www.browserstack.com/automate/capabilities?tag=selenium-4
      desiredCapabilities: {
        'bstack:options' : {
          local: 'false',
          userName: '${BROWSERSTACK_USER}',
          accessKey: '${BROWSERSTACK_KEY}',
        }
      }
    },

    browserstack.chrome': {
      extends: 'browserstack',
      desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions : {
          w3c: false
        }
      }
    },

    'browserstack.firefox': {
      extends: 'browserstack',
      desiredCapabilities: {
        browserName: 'firefox'
      }
    },

    'browserstack.ie': {
      extends: 'browserstack',
      desiredCapabilities: {
        browserName: 'IE',
        browserVersion: '11.0',
        'bstack:options' : {
          os: 'Windows',
          osVersion: '10',
          local: 'false',
          seleniumVersion: '3.5.2',
          resolution: '1366x768'
        }
      }
    }
  }
}

This section contains guides for getting started with most of the major browsers and setup instructions on how to configure the individual webdriver implementations to work with Nightwatch.

The individual drivers described here are usually standalone applications which are used to interact with the browsers via the WebDriver HTTP API. You can run them either directly, or through the Selenium Server.

Overview

GeckoDriver is a standalone application used to interact with Gecko-based browsers, such as Firefox. It is written in Rust and maintained by Mozilla.

Starting with Firefox 48, GeckoDriver is the only way to automate Firefox, the legacy FirefoxDriver which used to be part of Selenium is no longer supported. Internally it translates the HTTP calls into Marionette, Mozilla's automation protocol built into Firefox.

Download

GeckoDriver can be downloaded from the Releases page on GitHub. Release notes are also available there. Or you can use the geckodriver NPM package as a dependency in your project:

npm install geckodriver --save-dev

Selenium 2.x users are advised to use version v0.9, whereas Selenium 3 users should use the latest version.

Standalone Usage

Nightwatch can manage the GeckoDriver service automatically, as with other WebDriver services, such as ChromeDriver. To use GeckoDriver directly, add this to your nightwatch.json:

{ 
  "webdriver": {
    "start_process" : true,
    "server_path": "./bin/geckodriver-0.23",
    "cli_args": [
      "--log", "debug"
    ],
    "port": 4444
  },

  "test_settings" : {
    "default" : {
      "desiredCapabilities": {
        "browserName" : "firefox",
        "acceptInsecureCerts": true
      }
    }
  }
}

Usage with Selenium Server

If you're using GeckoDriver through Selenium Server, simply set the cli argument "webdriver.gecko.driver" to point to the location of the binary file. E.g.:

{
  "selenium" : {
    "start_process" : true,
    "server_path" : "./bin/selenium-server-standalone-3.{VERSION}.jar",
    "log_path" : "",
    "port" : 4444,
    "cli_args" : {
      "webdriver.gecko.driver" : "./bin/geckodriver"
    }
  }
}

GeckoDriver can also be used as a standalone application. Usage steps are documented on GitHub: https://github.com/mozilla/geckodriver#usage.

Command line usage
$ ./bin/geckodriver-0.23 -help
geckodriver 0.23.0

USAGE:
    geckodriver-0.23 [FLAGS] [OPTIONS]

FLAGS:
        --connect-existing    Connect to an existing Firefox instance
    -h, --help                Prints help information
        --no-e10s             Start Firefox without multiprocess support (e10s) enabled
    -V, --version             Prints version information
    -v                        Set the level of verbosity. Pass once for debug level logging and twice for trace level logging

OPTIONS:
    -b, --binary            Path to the Firefox binary, if no binary capability provided
        --log                Set Gecko log level [values: fatal, error, warn, info, config, debug, trace]
        --marionette-port     Port to use to connect to gecko (default: random free port)
        --host                Host ip to use for WebDriver server (default: 127.0.0.1)
    -p, --port                Port to use for WebDriver server (default: 4444)
Firefox Capabilities

GeckoDriver supports a capability named firefoxOptions which takes Firefox-specific preference values. Details are available on the GeckoDriver GitHub page: https://github.com/mozilla/geckodriver#firefox-capabilities.

Firefox Profile

Specifying the firefox profile can be done by setting the profile property in the firefoxOptions dictionary, as detailed above. This can be the base64-encoded zip of a profile directory and it may be used to install extensions or custom certificates.

Implementation Status

GeckoDriver is not yet feature complete, which means it does not yet offer full conformance with the WebDriver standard or complete compatibility with Selenium. Implementation status can be tracked on the Marionette MDN page.

Overview

ChromeDriver is a standalone server which implements the JSON Wire Protocol for Chromium, however it is currently in the process of transitioning to the W3C WebDriver spec.

It is available for Chrome on Android and Chrome on Desktop (Mac, Linux, Windows and ChromeOS).

Download

ChromeDriver can be downloaded from the ChromeDriver Downloads page. Or you can use the chromedriver NPM package as a dependency in your project:

npm install chromedriver --save-dev

Standalone Usage

Nightwatch can manage the ChromeDriver service automatically, as with other WebDriver services, such as GeckoDriver. To use ChromeDriver directly, configure Nightwatch as below:

{ 
  "webdriver": {
    "server_path": "node_modules/.bin/chromedriver",
    "cli_args": [
      "--verbose"
    ],
    "port": 9515
  },

  "test_settings" : {
    "default" : {
      "desiredCapabilities" : {
        "browserName" : "chrome"
      }
    }
  }
}

Selenium Server Usage

If you're using ChromeDriver through Selenium Server, simply set the cli argument "webdriver.chrome.driver" to point to the location of the binary file. E.g.:

{
  "selenium" : {
    "start_process" : true,
    "server_path" : "./bin/selenium-server-standalone-3.{VERSION}.jar",
    "log_path" : "",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "./bin/chromedriver"
    }
  }
}

ChromeOptions

You can specify Chrome options or switches using the chromeOptions dictionary, under the desiredCapabilities. Refer to the ChromeDriver website for a fill list of supported capabilities and options.

Example of detailed config
{ 
  "test_settings" : {
    "default" : {
      "desiredCapabilities" : {
        "browserName" : "chrome",
        "chromeOptions": {
          "args" : ["--no-sandbox"]
        },
        "loggingPrefs": {"driver": "INFO", "server": "OFF", "browser": "INFO"}
      }
    }
  }
}
Command line usage
$ ./bin/chromedriver -h
Usage: ./bin/chromedriver [OPTIONS]

Options
  --port=PORT                     port to listen on
  --adb-port=PORT                 adb server port
  --log-path=FILE                 write server log to file instead of stderr, increases log level to INFO
  --verbose                       log verbosely
  --version                       print the version number and exit
  --silent                        log nothing
  --url-base                      base URL path prefix for commands, e.g. wd/url
  --port-server                   address of server to contact for reserving a port
  --whitelisted-ips               comma-separated whitelist of remote IPv4 addresses which are allowed to connect to ChromeDriver

Overview

Microsoft WebDriver is a standalone server which implements the WebDriver protocol for the Edge browser. It is supported by Windows 10 and onwards.

Download

WebDriver for Microsoft Edge is now a Windows Feature on Demand. To install run the following in an elevated command prompt:

DISM.exe /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0

More details about installation and usage documentation are available on the official Microsoft WebDriver homepage.

Selenium Server Usage

If you're using Microsoft WebDriver through Selenium Server, simply set the cli argument "webdriver.edge.driver" to point to the location of the binary file. E.g.:

{
  "selenium" : {
    "start_process" : true,
    "server_path" : "bin/selenium-server-standalone-3.{VERSION}.jar",
    "log_path" : "",
    "port" : 4444,
    "cli_args" : {
      "webdriver.edge.driver" : "bin/MicrosoftWebDriver.exe"
    }
  },
  "test_settings" : {
    "default" : {
      "selenium_port"  : 4444,
      "selenium_host"  : "localhost",

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

Standalone Usage

If you're only running your tests against Edge, running the EdgeDriver standalone can be slightly faster. Also there is no dependency on Java.

This requires a bit more configuration and you will need to start/stop the EdgeDriver:

1) First, disable Selenium Server, if applicable:
{
  "selenium" : {
    "start_process" : false
  }
}
2) Configure the port and default path prefix.

Microsoft WebDriver runs by default on port 9515. We also need to clear the default_path_prefix, as it is set by default to /wd/hub, which is what selenium is using.

{
  "test_settings" : {
    "default" : {
      "selenium_port"  : 17556,
      "selenium_host"  : "localhost",
      "default_path_prefix" : "",

      "desiredCapabilities": {
        "browserName": "MicrosoftEdge",
        "acceptSslCerts": true
      }
    }
  }
}
3) Start the MicrosoftWebDriver server

From the Windows CMD prompt, simply CD to the folder where the MicrosoftWebDriver.exe binary is located and run:

C:\nightwatch\bin>MicrosoftWebDriver.exe
[13:44:49.515] - Listening on http://localhost:17556/

Full command line usage:

C:\nightwatch\bin>MicrosoftWebDriver.exe -h
Usage:
 MicrosoftWebDriver.exe --host= --port= --package= --verbose
Implementation Status

EdgeDriver is not yet feature complete, which means it does not yet offer full conformance with the WebDriver standard or complete compatibility with Selenium. Implementation status can be tracked on the Microsoft WebDriver homepage.