Knowledge Base

  1. Home
  2. Knowledge Base
  3. General
  4. How-to
  5. 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:

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

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

client.waitForElementPresent('body', 1000);

// continue if failed
browser.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:

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

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

Leave a Reply 0 comments

Leave a Reply: