Support & information center

How to wait and click on elements

When writing your test scripts, you may find yourself needing to click a button. In many cases, this is how the call will look like:

client .click(“#callButton”) .pause(50000);

What we want to do here is show a slightly different mechanism that doesn’t use the .pause() command. Instead of using pauses, Nightwatch API provides the alternative of waiting for an element based on presence and visibility.

.waitForElementPresent()

.waitForElementPresent() waits a given amount of milliseconds for an element to be present in the page before performing any other commands or assertions.

Parameters

NameTypedescription
selectorstringThe selector (CSS / Xpath) used to locate the element.
timenumberThe number of milliseconds to wait. The runner performs repeated checks every 500 ms.
callback (Optional)functionOptional callback function to be called when the command finishes.
message
(Optional)
stringOptional 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).

Examples

client.waitForElementPresent('body', 1000); // continue if failed client.waitForElementPresent('body', 1000, false); // with callback client.waitForElementPresent('body', 1000, function() { // do something while we're here }); // custom Error message client.waitForElementPresent('body', 1000, 'Element is not present!'); // many combinations possible - the message is always the last argument client.waitForElementPresent('body', 1000, false, function() {}, ' Element is not present');

.waitForElementVisible()

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

Parameters

NameTypedescription
SelectorstringThe selector (CSS / Xpath) used to locate the element.
TimenumberThe number of milliseconds to wait. The runner performs repeated checks every 500 ms.
callback
Optional
functionOptional callback function to be called when the command finishes.
message
Optional
stringOptional 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).

Examples

client.waitForElementVisible('body', 1000); // continue if failed client.waitForElementVisible('body', 1000, false); // with callback client.waitForElementVisible('body', 1000, function() { // do something while we're here }); // custom Error message client.waitForElementVisible('body', 1000, 'Element not visible!'); // many combinations possible - the message is always the last argument client.waitForElementVisible('body', 1000, false, function() {}, 'Element not visible!');

Was this article helpful?

Related Articles