Skip to main content

Script Examples

Locating elements by using CSS selectors

client.useCss();

This command sets element locator strategy to CSS. CSS is also the default strategy used by Nightwatch.

client => {
// Example of locating elements using CSS selectors
client
// Navigate to website bing.com
.url("https://www.bing.com")

// Wait up to 10 seconds until page is visible and take a screenshot
.waitForElementVisible('.dimmer', 10 * 1000)
.takeScreenshot("bing.png")

// Type 'QA Processes' in the search bar and press 'Enter'
.waitForElementVisible("[type=search]", 10 * 1000)
.setValue("[type=search]", ["QA Processes", client.Keys.ENTER])

// Wait up to 10 seconds until search results are visible and take a screenshot
.waitForElementVisible("[aria-label='Search Results']", 10 * 1000)
.takeScreenshot("search_results.png");
}

Locating elements by using xPath selectors

client.useXpath();

Sets the locate strategy for selectors to XPath. It is possible to use both XPath and CSS strategies by switching back and forth.

client => {
// Example of locating elements using XPATH selectors
client
// Navigate to website bing.com
.url("https://www.bing.com")

// Set the locate strategy for selectors to xpath
.useXpath()

// Wait up to 10 seconds until page is visible and take a screenshot
.waitForElementVisible("//*[contains(@class, 'dimmer')]", 10 * 1000)
.takeScreenshot("bing.png")

// Type 'QA Processes' in the search bar and press 'Enter'
.waitForElementVisible("//*[@type='search']", 10 * 1000)
.setValue("//*[@type='search']", ["QA Processes", client.Keys.ENTER])

// Wait up to 10 seconds until search results are visible and take a screenshot
.waitForElementVisible("//*[@aria-label='Search Results']", 10 * 1000)
.takeScreenshot("search_results.png");
}

Using Nightwatch assertions

Nightwatch native assertions are called by two methods, depending on the expected result after error is asserted: .assert and .verify

Once this assertion fails, test is ended and any assertions further in the script are skipped:

client.assert.visible(".non-existing-element-class");

This assertion will log the failure and script execution continues on.

client.verify.visible(".non-existing-element-class");
client => {
// Example of using Nightwatch assertions
client
.url('https://www.ecosia.org')
.waitForElementVisible('.indexpage', 10 * 1000)

// Check if the page url contains given value, otherwise stop the test
.assert.urlEquals('https://www.ecosia.org/')

// Verify if the page title contains given value, otherwise log error
.verify.title(
'Ecosia - the search engine that plants trees'
)

// Dismiss cookie consent banner
.click('.cookie-consent__actions > button:nth-of-type(2)')

// Scroll map section into view
.execute(() => {
var element = document.querySelector('.map-section');
if (element) {
element.scrollIntoView();
}
})

// Check if the map is visible, otherwise log error
.verify.visible('.map-section')
.takeScreenshot('map.png');
}