API Reference


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.

Parameters

Name Type description
windowHandle string
width number
height number
callback
Optional
function

Optional callback function to be called when the command finishes.

Usage

 this.demoTest = function (browser) {

   // Return the size of the specified window. If the :windowHandle URL parameter is "current", the size of the currently active window will be returned.
   browser.windowSize('current', function(result) {
     console.log(result.value);
   });

   // Change the size of the specified window.
   // If the :windowHandle URL parameter is "current", the currently active window will be resized.
   browser.windowSize('current', 300, 300, function(result) {
     console.log(result.value);
   });
}

API Reference

The built-in extendable assert/verify library is available on the Nightwatch instance as two namespaces containing the same methods which 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.



The following will end the test:
browser.assert.visible('.non_existing');

However this will just log the failure and continue:
browser.verify.visible('.non_existing');

Node.js Assert Module

The methods from the Node.js assert module are also available on the .assert/.verify namespaces and can be used.

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

assert.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');
};

assert.attributeEquals()

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

Parameters:
Name Type description
selector 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");
};

assert.containsText()

Checks if the given element contains the specified text.

Parameters:
Name Type description
selector 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");
};

assert.cssClassPresent()

Checks if the given element has the specified CSS class.

Parameters:
Name Type description
selector string TThe selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.cssClassNotPresent()

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.cssProperty()

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.elementPresent()

Checks if the given element exists in the DOM.

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.elementNotPresent()

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.hidden()

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.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");
};

assert.urlContains()

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('nightwatchjs.org');
};

assert.urlEquals()

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('https://www.google.com');
};

assert.value()

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.valueContains()

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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");
};

assert.visible()

Checks if the given element is visible on the page.

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
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');
  browser.assert.visible({selector: '.should_be_visible'});
  browser.assert.visible({selector: '.should_be_visible', supressNotFoundErrors: true});
};

Nightwatch provides a fluent 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, also adding new capabilities over the classic assert interface.

It uses a chain-able 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');
};

.startsWith(value)/.endsWith(value)

Same as equal / contain / match.

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

  browser.expect.element('#main').text.to.startWith('The');
};

.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);
};

Expect assertions operating on a single cookie after retrieving the entire cookie string, using .getCookies().

Syntax:
browser.expect.cookie('cookie-name', ['cookie-domain'])
this.demoTest = function (browser) {
  browser.expect.cookie('cookie-name').to.contain('cookie-value');
  browser.expect.cookie('cookie-name').to.match(/regex/);
  browser.expect.cookie('loginCookie', 'example.org').to.contain('cookie-value');
};
Parameters:
Name Type description
name String The name of the cookie to be inspected.
domain
Optional
String The domain name on which the cookie is set to.

Expect assertions operating on a single element, specified by its CSS/Xpath selector.

Syntax:
browser.element('#selector')
Parameters:
Name Type description
selector String The CSS/XPath selector of the element to be inspected.

.a(type)Suggest edits

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

Parameters:
Name Type description
type string

The expected type

message
Optional
string

Optional log message to display in the output. If missing, one is displayed by default.

Usage:
this.demoTest = function (browser) {
  browser.expect.element('#q').to.be.an('input');
  browser.expect.element('#q').to.be.an('input', 'Testing if #q is an input');
  browser.expect.element('#w').to.be.a('span');
}

.activeSuggest edits

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

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

.attribute(name)Suggest edits

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

Parameters:
Name Type description
attribute string

The attribute name

message
Optional
string

Optional log message to display in the output. If missing, one is displayed by default.

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.not.have.attribute('data-attr', 'Testing if body does not have 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)Suggest edits

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

Parameters:
Name Type description
property string

The css property name

message
Optional
string

Optional log message to display in the output. If missing, one is displayed by default.*

Usage:
this.demoTest = function (browser) {
  browser.expect.element('#main').to.have.css('display');
  browser.expect.element('#main').to.have.css('display', 'Testing for 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/);
};

.enabledSuggest edits

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

.presentSuggest edits

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

.selectedSuggest edits

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

.textSuggest edits

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/);
};

.valueSuggest edits

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/);
};

.visibleSuggest edits

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

Expect assertions operating on a collection of elements, specified by a CSS/Xpath selector. So far only .count is available.

Syntax:
browser.elements('#selector')
Parameters:
Name Type description
selector String The CSS/XPath selector of the collection of elements to be inspected.

.elements().count

Checks if the number of elements specified by a selector is equal or not to a given value.

Usage:
this.demoTest = function (browser) {
  browser.expect.elements('div').count.to.equal(10);
  browser.expect.elements('p').count.to.not.equal(1);
}

Retrieves the page title value in order to be used for performing equal, match or contains assertions on it.

Usage:
this.demoTest = function (browser) {
  browser.expect.title().to.contain('value');
  browser.expect.title().to.match(/value/);
};

Retrieves the page url value in order to be used for performing equal, match or contains assertions on it.

Usage:
this.demoTest = function (browser) {
  browser.expect.url().to.contain('https://');
  browser.expect.url().to.endWidth('.org');
};

Page objects provide an additional layer of abstraction for test case creation. Page objects are defined in modules and parsed into factory functions that create page object instances. These factories are accessible through the page reference within the command API (accessible through the browser object) using the name of the module that defines them.

Example:

module.exports = {
  // can be string or function
  url: function () {
    return this.api.launchUrl;
  },
  elements: {
    // shorthand, specifies selector
    mySubmitButton: 'input[type=submit]'

    // full
    myTextInput: {
      selector: 'input[type=text]',
      locateStrategy: 'css selector'
    }
  },
  commands: [
    {
      myCustomPause: function () {
        this.api.pause(this.props.myPauseTime);
      }
    }
  ],
  // object version (best considered immutable)
  props: {
    myPauseTime: 1000
  },

  sections: {
    myFooterSection: {
      selector: '#my-footer',
      locateStrategy: 'css selector',
      elements: {
        myLogo: {
          selector: '.my-logo',
          locateStrategy: 'css selector'
        }
      },
      commands: [
        {
          myMoveToLogo: function () {
            this.moveToElement('@myLogo', this.props.myLogoX, this.props.myLogoY);
          }
        }
      ],
      // function version (recommended)
      props: function () {
        return {
          myLogoX: 10,
          myLogoY: 10
        };
      },
      sections: {
        // additional, nested sections
      }
    }
  }
};

Page Object Module

Name Type description
commands Array A list of objects containing functions to represent methods added to the page object instance.
elements Object | Array An object, or array of objects, of named element definitions to be used as element selectors within element commands called from the page object.
props Object | Function An object or a function returning an object representing a container for user variables. Props objects are copied directly into the props property of the page object instance.
sections Object An object of named sections definitions defining the sections within the page object.
url String | Function A url or function returning a url to be used in a url() command when the page's navigate() method is called.

Page Object Instance

Page object module definitions are used to define page object instances when their respective factory functions within the page reference of the standard command API is called.

const myPageObject = browser.page.MyPage(); // defined in MyPage.js module

Every time a factory function like MyPage above is called, a new instance of the page object is created.

Page Object Properties

Name Type description
api Object A reference providing access to the full Nightwatch command API, usually known as browser in test cases. This is used to access those commands that are not part of the subset of commands within the page object API.
elements Object A map of Element objects used by element selectors.
name string The name of the page object as defined by its module name (not including the extension). This is the same name used to access the page object factory from the page reference in the command API.
props Object A reference to props object assigned from the module definition.

Note: this will be the same props object for all instances of the page object if defined as an object instance within the page object module. If you wish for each props object to be unique, define props in the module as a function that would return a new props object for each new page object instance.
section Object A map of Sections objects defined for the page object. This will only contain sections within the page object module's root sections definition. Nested sections are accessible through their parent section's own section reference.
url string|Function The url value from the page object module, either a string or a function depending on how it was defined there.

Page Object Methods

Navigates to the resolved url defined for the page object using the command API's url() command. This command is generally used in place of the command API's url() when working with page objects because the url member of the page object is the user-defined url string or function and not the call used to navigate to a url.

Element Instances

Element instances encapsulate the definition used to handle element selectors. Generally you won't need to access them directly, instead referring to them using their @-prefixed names for selector arguments, but they are available through a page object or section's elements property.

Section Instances

Page object section instances are accessed from the section property of a page object instance (note that this is the singular version of "section" whereas the plural version, "sections", was used in the module definition). Sections are created automatically through the page object factory and are available directly as properties from the section reference.

const myPageObject = browser.page.MyPage();
const mySection = myPageObject.section.MySection; // from a `sections: {}` block in page object

Page Object Commands

The Nightwatch command and assertions API is inherited by page objects.

Custom Commands

Name Type description
commands Array A list of objects containing functions to represent methods added to the page object instance.

Page object commands considerations:

  • Access: Page object commands are defined within page object modules. They can be in the module root object within the commands list or within section definitions (also in a commands), but only exist for the definition they're within.

    Page object commands in the module root commands are not available in child sections and section commands are not available in parent sections or the root page object.
  • Context: Page object command context (the value of this) is the page object (for sections its the section object).
  • Execution: Page object commands are not called from within the command queue. Code in a page object command is executed immediately when the function is called.
  • Chaining: Page object commands must return a value for chaining. This can be anything, but it's recommended you stick to this to allow your commands to be chained in the context of the page object instance.

Nightwatch provides the basic WebDriver protocol mappings and also various composite commands to ensure a more fluent and convenient syntax for writing tests.

  • composite commands - such as getValue or isVisible, usually incorporate two or more WebDriver protocol commands
  • protocol commands - are most of the times simple mappings to the W3C WebDriver protocol or, in some cases, its predecessor - the Selenium JsonWireProtocol protocol.

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

Callback function

Each method below allows a callback argument to be passed as the last argument. The callback function will then be called after the command is completed with the main API (browser) as the context and the response object as argument.


this.demoTest = function (browser) {
  browser.click("#main ul li a.first", function(result) {
    this.assert.ok(browser === this);
    this.assert.ok(typeof result == "object");
  });
};

Promises in callbacks

If the callback happens to return a Promise, the test runner will wait for the promise to settle (i.e. resolve or reject) before continuing with the rest of the commands.


module.exports = {
  demoTest: function (browser) {
    browser
      .init()
      .getText("#main ul li", function(result) {
        return new Promise(function(resolve, reject) {
          setTimeout(function() {
            console.log('Value:', result.value);
            resolve();
          }, 1000);
        });
      })
      .click('#login button');
  },

  demoTestAsync: async function(browser) {
    await browser.init();
    const text = await browser.getText("#main ul li", function(result) {
      return Promise.resolve(resolve.value);
    });
console.log('text', text); } };

If you're missing the individual command usage details, please note it has been moved into the dedicated command page (e.g. /api/clearValue.html). Simply click a command name to open its page.

The commands listed below allow lookup of individual elements and collections of elements. Element retrieval searches are performed using a provided selector specified usually as a CSS selector or, less often, as an Xpath selector.

More info on locator strategies can be found on the WebDriver page.

Each element has an internal associated Web Element reference (a UUID) that uniquely identifies the element across all browsing contexts.

.element() Suggest edits

Search for an element on the page, starting from the document root. The located element will be returned as a web element JSON object.
First argument to be passed is the locator strategy, which is detailed on the WebDriver docs.

The locator stragy can be one of:

  • css selector
  • link text
  • partial link text
  • tag name
  • xpath
Parameters:
Name Type description
using string

The locator strategy to use.

value string

The search target.

callback function

Callback function which is called with the result value.

See more...

.elementIdElement() Suggest edits

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

This command operates on a protocol level and requires a Web Element ID. Read more on Element retrieval on the W3C WebDriver spec page.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

using string

The locator strategy to use.

value string

The search target.

callback function

Callback function which is called with the result value.

See more...

.elementIdElements() Suggest edits

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

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

using string

The locator strategy to use.

value string

The search target.

callback function

Callback function which is called with the result value.

See more...

.elementIdEquals() Suggest edits

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

This command is deprecated and is only available on the JSON Wire protocol

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

otherId string

The Web Element ID of the other element to compare against.

callback function

Callback function which is called with the result value.

See more...

.elements() Suggest edits

Search for multiple elements on the page, starting from the document root. The located elements will be returned as web element JSON objects.
First argument to be passed is the locator strategy, which is detailed on the WebDriver docs.

The locator strategy can be one of:

  • css selector
  • link text
  • partial link text
  • tag name
  • xpath
Parameters:
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.

See more...

.waitForElementPresent() Suggest edits

Waits a given time in milliseconds (default 5000ms) 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, the default timeout can be specified as a global waitForConditionTimeout property (in milliseconds).

Parameters:
Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string

The selector (CSS / Xpath) used to locate the element.

time=waitForConditionTimeout
Optional
number

The total number of milliseconds to wait before failing.

poll=waitForConditionPollInterval
Optional
number

The number of milliseconds to wait between checks. You can use this only if you also specify the time parameter.

abortOnFailure=abortOnAssertionFailure
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. To set this globally you can define a property abortOnAssertionFailure in your globals.

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).

See more...

.waitForElementNotPresent() Suggest edits

Opposite of waitForElementPresent. Waits a given time in milliseconds (default 5000ms) 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).

Parameters:
Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string

The selector (CSS / Xpath) used to locate the element.

time=waitForConditionTimeout
Optional
number

The total number of milliseconds to wait before failing.

poll=waitForConditionPollInterval
Optional
number

The number of milliseconds to wait between checks. You can use this only if you also specify the time parameter.

abortOnFailure=abortOnAssertionFailure
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. To set this globally you can define a property abortOnAssertionFailure in your globals.

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).

See more...

.waitForElementVisible() Suggest edits

Waits a given time in milliseconds (default 5000ms) 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).

Parameters:
Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string

The selector (CSS / Xpath) used to locate the element.

time=waitForConditionTimeout
Optional
number

The total number of milliseconds to wait before failing.

poll=waitForConditionPollInterval
Optional
number

The number of milliseconds to wait between checks. You can use this only if you also specify the time parameter.

abortOnFailure=abortOnAssertionFailure
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. To set this globally you can define a property abortOnAssertionFailure in your globals.

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).

See more...

.waitForElementNotVisible() Suggest edits

Opposite of waitForElementVisible. Waits a given time in milliseconds (default 5000ms) 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).

Parameters:
Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string

The selector (CSS / Xpath) used to locate the element.

time=waitForConditionTimeout
Optional
number

The total number of milliseconds to wait before failing.

poll=waitForConditionPollInterval
Optional
number

The number of milliseconds to wait between checks. You can use this only if you also specify the time parameter.

abortOnFailure=abortOnAssertionFailure
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. To set this globally you can define a property abortOnAssertionFailure in your globals.

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).

See more...

The element interaction commands provide a high-level instruction set for manipulating form controls. Unlike actions, they will implicitly scroll elements into view and check that it is an interactable element.

Details on how WebDriver checks if the element can be interacted with are available on the WebDriver Element interactability page.

.clearValue() Suggest edits

Clear a textarea or a text input element's value. Starting with v1.1 clearValue() will wait for the element to be present (until the specified timeout).

If the element is not found, an error is thrown which will cause the test to fail. Starting with v1.2 you can suppress element not found errors by specifying the suppressNotFoundErrors flag.

Parameters:
Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string|object

The selector (CSS/Xpath) used to locate the element. Can either be a string or an object which specifies element properties.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.click() Suggest edits

Simulates a click event on the given DOM element. The element is scrolled into view if it is not already pointer-interactable. See the WebDriver specification for element interactability.

Starting with v1.1 click() will also wait for the element to be present (until the specified timeout). * If the element is not found, an error is thrown which will cause the test to fail. Starting with v1.2 you can suppress element not found errors by specifying the suppressNotFoundErrors flag.

Parameters:
Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string

The CSS/Xpath selector used to locate the element.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.keys() Suggest edits

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.

Parameters:
Name Type description
keysToSend Array

The keys sequence to be sent.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.moveToElement() Suggest edits

Move the mouse by an offset of the specified element. 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.

Parameters:
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.

See more...

.setValue() Suggest edits

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.

setValue does not clear the existing value of the element. To do so, use the clearValue() 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 browser.Keys.

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

inputValue 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.

See more...

.submitForm() Suggest edits

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.

Parameters:
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.

See more...

Details on how WebDriver checks if the element is displayed are available on the WebDriver Element Displayedness page.

.elementActive() Suggest edits

Get the element on the page that currently has focus. The element will be returned as a Web Element JSON object.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

.getAttribute() Suggest edits

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

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

attribute string

The attribute name to inspect.

callback function

Callback function which is called with the result value.

Returns
Type description
* The value of the attribute

See more...

.getCssProperty() Suggest edits

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

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

cssProperty string

The CSS property to inspect.

callback function

Callback function which is called with the result value.

Returns
Type description
* The value of the css property

See more...

.getElementSize() Suggest edits

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

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

Returns
Type description
{width: number, height: number} The width and height of the element in pixels

See more...

.getTagName() Suggest edits

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

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

Returns
Type description
number The element's tag name, as a lowercase string.

See more...

.getText() Suggest edits

Returns the visible text for the element. Starting with v1.1 getText() will also wait for the element to be present (until the specified timeout).

Uses elementIdText protocol command.

Parameters:
Name Type description
using
Optional
string

The locator strategy to use. See W3C Webdriver - locator strategies

selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

Returns
Type description
string The element's visible text.

See more...

.getValue() Suggest edits

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

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

Returns
Type description
string The element's value.

See more...

.isVisible() Suggest edits

Determine if an element is currently displayed. Starting with v1.2 you can suppress element not found errors, in case the element is not found on the page, by specifying the suppressNotFoundErrors flag.

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

See more...

.getLocation() Suggest edits

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.

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

Returns
Type description
{x:number, y:number} The X and Y coordinates for the element on the page.

See more...

.getLocationInView() Suggest edits

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

Parameters:
Name Type description
selector string

The CSS/Xpath selector used to locate the element.

callback function

Callback function which is called with the result value.

Returns
Type description
{x: number, y: number} The X and Y coordinates for the element on the page.

See more...

The commands in this section operate on a low-level HTTP protocol level and are only accepting Web Element IDs as parameters. These commands are usually only useful in more complex scenarios, such as building custom commands or custom assertions.

To retrieve the Web Element ID use either the .element() or the .elements() commands.

.elementIdAttribute() Suggest edits

Get the value of an element's attribute.

Parameters:
Name Type description
webElementId string

ID of the element to route the command to.

attributeName string

The attribute name

callback function

Callback function which is called with the result value.

See more...

.elementIdClear() Suggest edits

Scrolls into view a submittable element excluding buttons or editable element, and then attempts to clear its value, reset the checked state, or text content.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.elementIdClick() Suggest edits

Scrolls into view the element and clicks the in-view center point. If the element is not pointer-interactable, an element not interactable error is returned.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.elementIdCssProperty() Suggest edits

Retrieve the computed value of the given CSS property of the given element.

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).

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

cssPropertyName string
callback function

Callback function which is called with the result value.

See more...

.elementIdDisplayed() Suggest edits

Determine if an element is currently displayed.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback function

Callback function which is called with the result value.

See more...

.elementIdEnabled() Suggest edits

Determine if an element is currently enabled.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback function

Callback function which is called with the result value.

See more...

.elementIdLocation() Suggest edits

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.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback function

Callback function which is called with the result value.

Returns
Type description
object The X and Y coordinates for the element on the page.

See more...

.elementIdLocationInView() Suggest edits

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

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.elementIdName() Suggest edits

Retrieve the qualified tag name of the given element.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback function

Callback function which is called with the result value.

See more...

.elementIdSelected() Suggest edits

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

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback function

Callback function which is called with the result value.

See more...

.elementIdSize() Suggest edits

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

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback function

Callback function which is called with the result value.

See more...

.elementIdText() Suggest edits

Returns the visible text for the element.

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback function

Callback function which is called with the result value.

See more...

.elementIdValue() Suggest edits

Scrolls into view the form control element and then sends the provided keys to the element, or returns the current value of the element. In case the element is not keyboard interactable, an element not interactable error is returned.

Parameters:
Name Type description
webElementId string

The Web Element 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 function

Callback function which is called with the result value.

See more...

.submit() Suggest edits

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

Parameters:
Name Type description
webElementId string

The Web Element ID of the element to route the command to.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.execute() Suggest edits

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.
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.

Under the hood, if the body param is a function it is converted to a string with <function>.toString(). Any references to your current scope are ignored.

To ensure cross-browser compatibility, the specified function should not be in ES6 format (i.e. () => {}). If the execution of the function fails, the first argument of the callback contains error information.

Parameters:
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.

See more...

.executeAsync() Suggest edits

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.

The function to be injected receives the done callback as argument which needs to be called when the asynchronous operation finishes. The value passed to the done callback is returned to the client.
Additional arguments for the injected function may be passed as a non-empty array which will be passed before the done callback.

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

Parameters:
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.

See more...

.injectScript() Suggest edits

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

Parameters:
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.

See more...

.source() Suggest edits

Returns a string serialisation of the DOM of the current page.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

A WebDriver session represents the connection between a client and a remote WebDriver server. Read more on WebDriver page.

.end() Suggest edits

Ends the session. Uses session protocol command.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.getLog() Suggest edits

Gets a log from Selenium.

Parameters:
Name Type description
typeString string|function

Log type to request

callback function

Callback function which is called with the result value.

See more...

.getLogTypes() Suggest edits

Gets the available log types. More info about log types in WebDriver can be found here: https://github.com/SeleniumHQ/selenium/wiki/Logging

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

Returns
Type description
Array Available log types

See more...

.isLogAvailable() Suggest edits

Utility command to test if the log type is available.

Parameters:
Name Type description
typeString string|function

Type of log to test

callback function

Callback function which is called with the result value.

See more...

.session() Suggest edits

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

Parameters:
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 by default.

sessionId
Optional
string

The id of the session to get info about or delete.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.sessionLog() Suggest edits

Gets the text of the log type specified. To find out the available log types, use .getLogTypes().

Returns a log entry JSON object.

Parameters:
Name Type description
typeString string

Type of log to request. Can be one of: client, driver, browser, server

callback function

Callback function which is called with the result value.

Returns
Type description
Array Array of the text entries of the log.

See more...

.sessionLogTypes() Suggest edits

Gets an array of strings for which log types are available. This methods returns the entire WebDriver response, if you are only interested in the logs array, use .getLogTypes() instead.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

.sessions() Suggest edits

Returns a list of the currently active sessions.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

.status() Suggest edits

Query the server's current status.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

.timeouts() Suggest edits

Configure or retrieve 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.

If called with only a callback as argument, the command will return the existing configured timeout values.

Parameters:
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 "pageLoad" (or "page load" for legacy JsonWire) 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.

See more...

.timeoutsAsyncScript() Suggest edits

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

Parameters:
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.

See more...

.timeoutsImplicitWait() Suggest edits

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.

Parameters:
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.

See more...

The commands in this section allow navigation to new URLs and introspection of the currently loaded url.

.back() Suggest edits

Navigate backwards in the browser history, if possible.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.forward() Suggest edits

Navigate forwards in the browser history, if possible.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.getTitle() Suggest edits

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

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

Returns
Type description
string The page title.

See more...

.init() Suggest edits

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.

Parameters:
Name Type description
url
Optional
string

Url to navigate to.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.refresh() Suggest edits

Refresh the current page.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.title() Suggest edits

Get the current page title.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

.url() Suggest edits

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

Parameters:
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

See more...

.urlHash() Suggest edits

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

Parameters:
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).

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.closeWindow() Suggest edits

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.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.fullscreenWindow() Suggest edits

Sets the current window state to fullscreen.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.getWindowPosition() Suggest edits

Retrieves the current window position.

For clients which are compatible with the W3C Webdriver API, getWindowPosition is an alias of getWindowRect.

The getWindowRect command returns both dimensions and position of the window, using the windowRect protocol command.

Parameters:
Name Type description
callback function

Callback function to be called when the command finishes.

See more...

.getWindowRect() Suggest edits

Change or get the window rect. This is defined as a dictionary of the screenX, screenY, outerWidth and outerHeight attributes of the window.

Its JSON representation is the following:

  • x - window's screenX attribute;
  • y - window's screenY attribute;
  • width - outerWidth attribute;
  • height - outerHeight attribute.

All attributes are in in CSS pixels. To change the window react, you can either specify width and height, x and y or all properties together.

Parameters:
Name Type description
callback function

Callback function to be called when the command finishes.

See more...

.getWindowSize() Suggest edits

Retrieves the current window size.

For clients which are compatible with the W3C Webdriver API, getWindowSize is an alias of getWindowRect.

The getWindowRect command returns both dimensions and position of the window, using the windowRect protocol command.

Parameters:
Name Type description
callback function

Callback function to be called when the command finishes.

See more...

.maximizeWindow() Suggest edits

Maximizes the current window.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.minimizeWindow() Suggest edits

Hides the window in the system tray. If the window happens to be in fullscreen mode, it is restored the normal state then it will be "iconified" - minimize or hide the window from the visible screen.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.openNewWindow() Suggest edits

Opens a new top-level browser window, which can be either a tab (default) or a separate new window.

This command is only available for W3C Webdriver compatible browsers.

Parameters:
Name Type description
type
Optional
string

Can be either "tab" or "window", with "tab" set to default if none is specified.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.resizeWindow() Suggest edits

Resizes the current window.

Parameters:
Name Type description
width number

The new window width.

height number

The new window height.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.setWindowPosition() Suggest edits

Sets the current window position.

Parameters:
Name Type description
offsetX number

The new window offset x-position.

offsetY number

The new window offset y-position.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.setWindowRect() Suggest edits

Change the window rect. This is defined as a dictionary of the screenX, screenY, outerWidth and outerHeight attributes of the window.

Its JSON representation is the following:

  • x - window's screenX attribute;
  • y - window's screenY attribute;
  • width - outerWidth attribute;
  • height - outerHeight attribute.

All attributes are in in CSS pixels. To change the window react, you can either specify width and height, x and y or all properties together.

Parameters:
Name Type description
options object

An object specifying either width and height, x and y, or all together to set properties for the window rect.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.setWindowSize() Suggest edits

Sets the current window size in CSS pixels.

Parameters:
Name Type description
width number

The new window width in CSS pixels

height number

The new window height in CSS pixels

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.switchWindow() Suggest edits

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 windowHandles command

Parameters:
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.

See more...

.window() Suggest edits

Change focus to another window or close the current window. Shouldn't normally be used directly, instead .switchWindow() and .closeWindow() should be used.

Parameters:
Name Type description
method string

The HTTP method to use. Can be either POST (change focus) or DELETE (close window).

handleOrName string

The window to change focus to.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.windowHandle() Suggest edits

Retrieve the current window handle.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

.windowHandles() Suggest edits

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

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

See more...

.windowMaximize() Suggest edits

Increases the window to the maximum available size without going full-screen.

Parameters:
Name Type description
handleOrName
Optional
string

Only required when using non-W3C Webdriver protocols (such as JSONWire). windowHandle URL parameter; if it is "current", the currently active window will be maximized.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.windowPosition() Suggest edits

Change or get the position 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 position.

Parameters:
Name Type description
windowHandle string
offsetX number
offsetY number
callback function

Callback function which is called with the result value.

See more...

.windowRect() Suggest edits

Change or get the window rect. This is defined as a dictionary of the screenX, screenY, outerWidth and outerHeight attributes of the window.

Its JSON representation is the following:

  • x - window's screenX attribute;
  • y - window's screenY attribute;
  • width - outerWidth attribute;
  • height - outerHeight attribute.

All attributes are in in CSS pixels. To change the window react, you can either specify width and height, x and y or all properties together.

Parameters:
Name Type description
options object

An object specifying either width and height, x and y, or all together to set properties for the window rect.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.windowSize() Suggest edits

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.

Parameters:
Name Type description
windowHandle string
width number
height number
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.frame() Suggest edits

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.

Parameters:
Name Type description
frameId
Optional
string|number

Identifier for the frame to change focus to.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.frameParent() Suggest edits

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

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

Retrieve or delete all cookies visible to the current page or set a cookie. Normally this shouldn't be used directly, instead the cookie convenience methods should be used: getCookie, getCookies, setCookie, deleteCookie, deleteCookies.

Parameters:
Name Type description
method string

Http method

callbackOrCookie
Optional
function|object

Optional callback function to be called when the command finishes.

See more...

.deleteCookie() Suggest edits

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

Parameters:
Name Type description
cookieName string

The name of the cookie to delete.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.deleteCookies() Suggest edits

Delete all cookies visible to the current page.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.getCookie() Suggest edits

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.

Parameters:
Name Type description
name string

The cookie name.

callback function

Callback function which is called with the result value.

Returns
Type description
object|null The cookie object as a selenium cookie JSON object or null if the cookie wasn't found.

See more...

.getCookies() Suggest edits

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.

Parameters:
Name Type description
callback function

The callback function which will receive the response as an argument.

Returns
Type description
Array. A list of cookies.

See more...

.setCookie() Suggest edits

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

Uses cookie protocol command.

Parameters:
Name Type description
cookie object

The cookie object.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.doubleClick() Suggest edits

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

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.mouseButtonClick() Suggest edits

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.

Parameters:
Name Type description
button string|number

The mouse button

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.mouseButtonDown() Suggest edits

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.

Parameters:
Name Type description
button string|number

The mouse button

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.mouseButtonUp() Suggest edits

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.

Parameters:
Name Type description
button string|number

The mouse button

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.moveTo() Suggest edits

Move the mouse by an offset of the specified Web Element ID or relative to the current mouse cursor, if no element is specified. If an element is provided but no offset, the mouse will be moved to the center of the element.

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.

Parameters:
Name Type description
webElementId
Optional
string

The Web Element 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.

See more...

.acceptAlert() Suggest edits

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

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.dismissAlert() Suggest edits

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.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.getAlertText() Suggest edits

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

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

Returns
Type description
string The text of the currently displayed alert.

See more...

.setAlertText() Suggest edits

Sends keystrokes to a JavaScript prompt() dialog.

Parameters:
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.

See more...

.saveScreenshot() Suggest edits

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

Parameters:
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.

See more...

.screenshot() Suggest edits

Take a screenshot of the current page.

Parameters:
Name Type description
log_screenshot_data boolean

Whether or not the screenshot data should appear in the logs when running with --verbose

callback function

Callback function which is called with the result value.

See more...

.contexts() Suggest edits

Get a list of the available contexts.

Used by Appium when testing hybrid mobile web apps. More info here: https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/hybrid.md.

Parameters:
Name Type description
callback function

Callback function to be called when the command finishes.

Returns
Type description
Array an array of strings representing available contexts, e.g 'WEBVIEW', or 'NATIVE'

See more...

.currentContext() Suggest edits

Get current context.

Parameters:
Name Type description
callback function

Callback function to be called when the command finishes.

Returns
Type description
string|null a string representing the current context or `null`, representing "no context"

See more...

.getOrientation() Suggest edits

Get the current browser orientation.

Parameters:
Name Type description
callback function

Callback function which is called with the result value.

Returns
Type description
string} The current browser orientation: {LANDSCAPE|PORTRAIT

See more...

.setContext() Suggest edits

Sets the context.

Parameters:
Name Type description
context string

context name to switch to - a string representing an available context.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.setOrientation() Suggest edits

Sets the browser orientation.

Parameters:
Name Type description
orientation string

The new browser orientation: {LANDSCAPE|PORTRAIT}

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.pause() Suggest edits

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

Parameters:
Name Type description
ms number

The number of milliseconds to wait.

callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.perform() Suggest edits

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

The callback signature can have up to two parameters.

  • no parameters: callback runs and perform completes immediately at the end of the execution of the callback.
  • one parameter: allows for asynchronous execution within the callback providing a done callback function for completion as the first argument.
  • two parameters: allows for asynchronous execution with the Nightwatch api object passed in as the first argument, followed by the done callback.
Parameters:
Name Type description
callback function

The function to run as part of the queue.

See more...

.useCss() Suggest edits

Sets the locate strategy for selectors to css selector, therefore every following selector needs to be specified as css.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...

.useXpath() Suggest edits

Sets the locate strategy for selectors to xpath, therefore every following selector needs to be specified as xpath.

Parameters:
Name Type description
callback
Optional
function

Optional callback function to be called when the command finishes.

See more...