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

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


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

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

Language Chains

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

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

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

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


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

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

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

.not

Negates any of assertions following in the chain.


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

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

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

.before(ms)/.after(ms)

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

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


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

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

.a(type)

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

.attribute(name)

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)

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

.enabled

Property that checks if an element is currently enabled.

Usage:

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

.present

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

Usage:

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

.selected

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

Usage:

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

.text

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

Usage:

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

.value

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

Usage:

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

.visible

Property that asserts the visibility of a specified element.

Usage:

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

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

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

This will end the test:

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

But this will just log the failure and continue:

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

Node.js Assert Module

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

Automatically retrying failed assertions

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

For example: retryAssertionTimeout = 2000

.attributeContains()

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

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

this.demoTest = function (browser) {

  browser.assert.attributeContains('#someElement', 'href', 'google.com');

};

.attributeEquals()

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

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

this.demoTest = function (browser) {

  browser.assert.attributeEquals("body", "data-attr", "some value");

};

.containsText()

Checks if the given element contains the specified text.

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

this.demoTest = function (browser) {

  browser.assert.containsText("#main", "The Night Watch");

};

.cssClassPresent()

Checks if the given element has the specified CSS class.

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

this.demoTest = function (browser) {

  browser.assert.cssClassPresent("#main", "container");

};

.cssClassNotPresent()

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

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

this.demoTest = function (browser) {

  browser.assert.cssClassNotPresent("#main", "container");

};

.cssProperty()

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

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

this.demoTest = function (browser) {

  browser.assert.cssProperty("#main", "display", "block");

};

.elementPresent()

Checks if the given element exists in the DOM.

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

this.demoTest = function (browser) {

  browser.assert.elementPresent("#main");

};

.elementNotPresent()

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

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

this.demoTest = function (browser) {

  browser.assert.elementNotPresent(".should_not_exist");

};

.hidden()

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

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

this.demoTest = function (browser) {

  browser.assert.hidden(".should_not_be_visible");

};

.title()

Checks if the page title equals the given value.

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

this.demoTest = function (browser) {

  browser.assert.title("Nightwatch.js");

};

.urlContains()

Checks if the current URL contains the given value.

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

this.demoTest = function (browser) {

  browser.assert.urlContains('google');

};

.urlEquals()

Checks if the current url equals the given value.

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

this.demoTest = function (browser) {

  browser.assert.urlEquals('http://www.google.com');

};

.value()

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

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

this.demoTest = function (browser) {

  browser.assert.value("form.login input[type=text]", "username");

};

.valueContains()

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

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

this.demoTest = function (browser) {

  browser.assert.valueContains("form.login input[type=text]", "username");

};

.visible()

Checks if the given element is visible on the page.

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

this.demoTest = function (browser) {

  browser.assert.visible(".should_be_visible");

};

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

The callback function

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


this.demoTest = function (browser) {

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

};

.clearValue()

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

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

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

.click()

Simulates a click event on the given DOM element. Uses elementIdClick 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.
Usage:

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

.closeWindow()

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

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

.deleteCookie()

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
The cookieName name of the cookie to delete.
callback
Optional
function Optional callback function to be called when the command finishes.
Usage:

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

.deleteCookies()

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

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

.end()

Ends the session. Uses session protocol command.

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

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

.getAttribute()

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

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

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

.getCookie()

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

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

.getCookies()

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.<object> A list of cookies.
Usage:

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

.getCssProperty()

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

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

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

.getElementSize()

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

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

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

.getLocation()

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

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

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

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

.getLocationInView()

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

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

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

.getLog()

Gets a log from selenium.

Parameters:
Name Type description
typeString string|function Log type to request
callback function Callback function which is called with the result value.
Usage:

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

.getLogTypes()

Gets the available log types. 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
Usage:

this.demoTest = function(client) {
  this.getLogTypes(function(typesArray) {
    console.log(typesArray);
  });
};

.getTagName()

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

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

.getText()

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

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 visible text.
Usage:

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

.getTitle()

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

Parameters:
Name Type description
callback function Callback function which is called with the result value.
Returns
Type description
string The page title.
Usage:

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

.getValue()

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

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

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

.init()

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

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

.injectScript()

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

this.demoTest = function(client) {
  this.injectScript("{script-url}", function() {
    // we're all done here.
  });
};

.isLogAvailable()

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

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

.isVisible()

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

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

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

.maximizeWindow()

Maximizes the current window.

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

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

.moveToElement()

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

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

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

.pause()

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

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

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

.perform()

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

Parameters:
Name Type description
callback function The function to run as part of the queue. Its 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 "api" object passed in as the first argument, followed by the done callback.
Usage:

this.demoTest = function (browser) {
  var elementValue;
  browser
    .getValue('.some-element', function(result) {
      elementValue = result.value;
    })
    // other stuff going on ...
    //
    // self-completing callback
    .perform(function() {
      console.log('elementValue', elementValue);
      // without any defined parameters, perform
      // completes immediately (synchronously)
    })
    //
    // asynchronous completion
    .perform(function(done) {
      console.log('elementValue', elementValue);
      // potentially other async stuff going on
      // on finished, call the done callback
      done();
    })
    //
    // asynchronous completion including api (client)
    .perform(function(client, done) {
      console.log('elementValue', elementValue);
      // similar to before, but now with client
      // potentially other async stuff going on
      // on finished, call the done callback
      done();
    });
};

.resizeWindow()

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

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

.saveScreenshot()

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

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

.setCookie()

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

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

.setValue()

See sessionsessionidelementidvalue

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

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

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

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

.setWindowPosition()

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

 this.demoTest = function (browser) {
   browser.setWindowPosition(0, 0);
 };

.submitForm()

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

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

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

.switchWindow()

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

To find out the window handle use window_handles protocol action

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

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

.urlHash()

Convenience method 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).
Usage:

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

.useCss()

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

this.demoTest = function (browser) {
  browser
    .useCss() // we're back to CSS now
    .setValue('input[type=text]', 'nightwatch');
};

.useXpath()

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

this.demoTest = function (browser) {
  browser
    .useXpath() // every selector now must be xpath
    .click("//tr[@data-recordid]/span[text()='Search Text']");
};

.waitForElementNotPresent()

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

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

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

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. 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).
Usage:

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

.waitForElementNotVisible()

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

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

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

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. 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).
Usage:

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

.waitForElementPresent()

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

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

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

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. 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).
Usage:

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

.waitForElementVisible()

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

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

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

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

Parameters:
Name Type description
selector string The selector (CSS / Xpath) used to locate the element.
time number The number of milliseconds to wait. The runner performs repeated checks every 500 ms.
abortOnFailure
Optional
boolean By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. 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).
Usage:

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

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

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

Sessions

A WebDriver session represents the connection between a local end and a specific remote end. Read more on WebDriver page.

.session()

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

 this.demoTest = function (browser) {
   browser.session(function(result) {
     console.log(result.value);
   });
   //
   browser.session('delete', function(result) {
     console.log(result.value);
   });
   //
   browser.session('delete', '12345-abc', function(result) {
     console.log(result.value);
   });
 };

.sessions()

Returns a list of the currently active sessions.

Parameters:
Name Type description
callback function Callback function which is called with the result value.
Usage:

 this.demoTest = function (browser) {
   browser.sessions(function(result) {
     console.log(result.value);
   });
 };

.timeouts()

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

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 "page load" for setting a page load timeout.
ms number The amount of time, in milliseconds, that time-limited commands are permitted to run.
callback
Optional
function Optional callback function to be called when the command finishes.

.timeoutsAsyncScript()

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.

.timeoutsImplicitWait()

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.

.status()

Query the server's current status.

Parameters:
Name Type description
callback function Callback function which is called with the result value.

.sessionLog()

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

Parameters:
Name Type description
typeString string Type of log to request.
callback function Callback function which is called with the result value.
Returns
Type description
Array Array of the text entries of the log.

.sessionLogTypes()

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.

Navigation

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

.url()

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

module.exports = {
 'demo Test' : function(browser) {
    browser.url(function(result) {
      // return the current url
      console.log(result);
    });
    //
    // navigate to new url:
    browser.url('{URL}');
    //
    //
    // navigate to new url:
    browser.url('{URL}', function(result) {
      console.log(result);
    });
  }
};

.back()

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.

.forward()

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.

.refresh()

Refresh the current page.

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

.title()

Get the current page title.

Parameters:
Name Type description
callback function Callback function which is called with the result value.

Command Contexts

.window()

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.

.windowHandle()

Retrieve the current window handle.

Parameters:
Name Type description
callback function Callback function which is called with the result value.

.windowHandles()

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.

.windowMaximize()

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

Parameters:
Name Type description
handleOrName
Optional
string 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.

.windowPosition()

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.

.windowSize()

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.

.frame()

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

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

.frameParent()

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.

Elements

These are the low level commands that are used to locate elements in the page. Each element has an associated web element reference (a UUID) that uniquely identifies the element across all browsing contexts. More details on elements are available on the WebDriver page.

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

.element()

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

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

module.exports = {
 'demo Test' : function(browser) {
    browser.element('css selector', 'body', function(res) {
      console.log(res)
    });
  }
};

.elements()

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

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.

.elementIdElement()

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

Parameters:
Name Type description
id string ID of the element to route the command to.
using string The locator strategy to use.
value string The search target.
callback function Callback function which is called with the result value.

.elementIdElements()

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

Parameters:
Name Type description
id string ID of the element to route the command to.
using string The locator strategy to use.
value string The search target.
callback function Callback function which is called with the result value.

.elementIdEquals()

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

Parameters:
Name Type description
id string ID of the element to route the command to.
otherId string ID of the element to compare against.
callback function Callback function which is called with the result value.

.elementActive()

Get the element on the page that currently has focus.

Parameters:
Name Type description
callback function Callback function which is called with the result value.

Element State

.elementIdAttribute()

Get the value of an element's attribute.

Parameters:
Name Type description
id 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.

.elementIdCssProperty()

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
id string ID of the element to route the command to.
cssPropertyName string
callback function Callback function which is called with the result value.

.elementIdDisplayed()

Determine if an element is currently displayed.

Parameters:
Name Type description
id string ID of the element to route the command to.
callback function Callback function which is called with the result value.

.elementIdEnabled()

Determine if an element is currently enabled.

Parameters:
Name Type description
id string ID of the element to route the command to.
callback function Callback function which is called with the result value.

.elementIdName()

Retrieve the qualified tag name of the given element.

Parameters:
Name Type description
id string ID of the element to route the command to.
callback function Callback function which is called with the result value.

.elementIdSelected()

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

Parameters:
Name Type description
id string ID of the element to route the command to.
callback function Callback function which is called with the result value.

.elementIdSize()

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
id string ID of the element to route the command to.
callback function Callback function which is called with the result value.

.elementIdText()

Returns the visible text for the element.

Parameters:
Name Type description
id string ID of the element to route the command to.
callback function Callback function which is called with the result value.

Element Interaction

.elementIdClear()

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
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

.elementIdClick()

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

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

.elementIdValue()

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
id string ID of the element to route the command to.
value
Optional
string|array|none Value to send to element in case of a POST
callback function Callback function which is called with the result value.

.keys()

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

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

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.

.submit()

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
id string ID of the element to route the command to.
callback
Optional
function Optional callback function to be called when the command finishes.

Element Location

.elementIdLocationInView()

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

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

.elementIdLocation()

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
id string ID of the element to route the command to.
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.

Document Handling

.source()

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.

.execute()

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

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

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

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

.executeAsync()

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

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

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

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

Cookies

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.

User Actions

.doubleClick()

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.

.mouseButtonClick()

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

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

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

.mouseButtonDown()

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.

.mouseButtonUp()

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.

.moveTo()

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

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

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

User Prompts

.acceptAlert()

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.

.dismissAlert()

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.

.getAlertText()

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.

.setAlertText()

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.

Screen Capture

.screenshot()

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.

Mobile Related

.getOrientation()

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

.setOrientation()

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.

.contexts()

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'

.currentContext()

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"

.setContext()

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.