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

Basic Assertions

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

Negate (".not") Assertions

Since version 1.3, all the assertions (including custom defined ones) will also have a ".not" counterpart, which can be used to assert the opposite.

And thus, assertions like elementNotPresent, cssClassNotPresent, hidden are obsolete and have been deprecated.

Example:


module.exports = {
  demoTest: function(browser) {
    browser.init();

    browser
      .assert.not.elementPresent('.not_present') // previously .assert.elementNotPresent()
      .assert.not.visible('.non_visible') // previously .assert.hidden()
      .assert.not.urlContains('http://');

    // ...
  }
}

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[.not].attributeContains()

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

Parameters:
Name Type description
definition string|object The selector (CSS/Xpath) used to locate the element. Can either be a string or an object which specifies [element properties](https://nightwatchjs.org/guide#element-properties).
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[.not].attributeEquals()

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

Parameters:
Name Type description
definition string|object The selector (CSS/Xpath) used to locate the element. Can either be a string or an object which specifies [element properties](https://nightwatchjs.org/guide#element-properties)
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[.not].containsText()

Checks if the given element contains the specified text.

Parameters:
Name Type description
definition string|object The selector (CSS/Xpath) used to locate the element. Can either be a string or an object which specifies [element properties](https://nightwatchjs.org/guide#element-properties).
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[.not].cssClassPresent()

Checks if the given element has the specified CSS class. Multiple css classes can be specified either as an array or a space-delimited string. In case the expected value is a space delimited string, the order is not taken into account - each value will individually be checked against.

Parameters:
Name Type description
definition string|object 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.cssClassPresent("#main", "container");
  browser.assert.cssClassPresent('#main', ['visible', 'container']);
  browser.assert.cssClassPresent('#main', 'visible container');
};

assert[.not].cssProperty()

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

Parameters:
Name Type description
definition string|object 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[.not].domPropertyContains()

Checks if the specified DOM property of a given element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). Several properties can be specified (either as an array or command-separated list). Nightwatch will check each one for presence.

Parameters:
Name Type description
definition string|object The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
domProperty string The DOM property name.
expected string|number The expected value of the DOM 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.domPropertyContains('#main', 'classList', 'visible');

  // in case the resulting property is an array, several elements could be specified
  browser.assert.domPropertyEquals('#main', 'classList', ['class-one', 'class-two']);
  browser.assert.domPropertyEquals('#main', 'classList', 'class-one,class-two');
};

assert[.not].domPropertyEquals()

Checks if the specified DOM property of a given element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). If the result value is JSON object or array, a deep equality comparison will be performed.

Parameters:
Name Type description
definition string|object The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies element properties.
domProperty string The DOM property name.
expected string|number The expected value of the DOM 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.domPropertyEquals('#main', 'className', 'visible');

  // deep equal will be performed
  browser.assert.domPropertyEquals('#main', 'classList', ['class-one', 'class-two']);

  // split on ',' and deep equal will be performed
  browser.assert.domPropertyEquals('#main', 'classList', 'class-one,class-two']);
};

assert[.not].elementPresent()

Checks if the given element exists in the DOM.

Parameters:
Name Type description
definition string|object 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[.not].enabled()

Checks if the given element is enabled (as indicated by the 'disabled' attribute).

Parameters:
Name Type description
definition string|object 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.enabled('.should_be_enabled');
   browser.assert.enabled({selector: '.should_be_enabled'});
  browser.assert.enabled({selector: '.should_be_enabled', supressNotFoundErrors: true});
};

assert[.not].selected()

Checks if the given element is selected.

Parameters:
Name Type description
definition string|object 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.selected('#main select option.first');
};

assert[.not].value()

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

Parameters:
Name Type description
definition string|object 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[.not].valueContains()

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

Parameters:
Name Type description
definition string|object 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[.not].visible()

Checks if the given element is visible on the page.

Parameters:
Name Type description
definition string|object 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});
};

assert[.not].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[.not].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[.not].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://nightwatchjs.org');
};

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

.startWith(value)/.endWith(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);
};

.property(name)Suggest edits

Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the Element doc at MDN.

Parameters:
Name Type description
property string

The 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('body').to.have.property('className').equals('test-class');
  browser.expect.element('body').to.have.property('className').matches(/^something\ else/);
  browser.expect.element('body').to.not.have.property('classList').equals('test-class');
  browser.expect.element('body').to.have.property('classList').deep.equal(['class-one', 'class-two']);
  browser.expect.element('body').to.have.property('classList').contain('class-two');
};

.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.endWith('.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) {
    const text = await browser.init().getText("#main ul li", function(result) {
      return Promise.resolve(result.value);
    });
console.log('The text is', 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.