Example test scripts
Locating elements
- JavaScript + Nightwatch.js
- Java + TestUI
- Python + Py-TestUI
The command below sets the element locator strategy to CSS. CSS is also the default strategy used by Nightwatch - so unless you have already switched to a different strategy beforehand, you do not actually need to execute this command.
client.useCss();
The next command, however, sets the element locator strategy to XPath.
client.useXpath();
It is possible to use both strategies by switching back and forth.
Example #1: using CSS selectors to locate elements
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)
.saveScreenshot("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)
.saveScreenshot("search_results.png");
}
Example #2: using XPath selectors to locate elements
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)
.saveScreenshot("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)
.saveScreenshot("search_results.png");
}
By using a general CSS selector
UIElement element = E(byCssSelector("your.Id"));
By using a specific element's ID
UIElement element = E(byId("your.Id"));
By using XPath
UIElement element = E(byXpath("//some"));
It is possible to mix and match these strategies - it is not required to stick to one throughout the entire script.
Example: using CSS selectors to locate elements
public void testUIWithLoadero() {
// Example of locating elements using CSS selector
open("https://www.bing.com")
// Wait 10 seconds until page is visible
.setElement(byCssSelector(".dimmer"))
.waitFor(10)
.untilIsVisible()
// Save a screenshot of https://bing.com website
.saveScreenshot("website_bing.png")
// Find search bar element
.setElement(byCssSelector("[type=search]"))
// Type "QA Processes" in it
.sendKeys("QA Processes")
// Find search button and click it
.setElement(byCssSelector("#search_icon")).click()
// Wait for search results to become visible
.setElement(byCssSelector("[aria-label='Search Results']"))
.waitFor(10)
.untilIsVisible()
// Take a screenshot of the search results
.saveScreenshot("search_results.png");
}
By using a general CSS selector
element = e(driver, "css", ".some-class")
By using a specific element's ID
element = e(driver, "id", "some-id")
By using the name of a specific class
element = e(driver, "className", "some-class")
By using the name
property
element = e(driver, "name", "some-name")
By using XPath
element = e(driver, "xpath", "//some-element")
Example #1: using CSS selectors to locate elements
def test(driver: TestUIDriver):
def move_to_element(element):
# Moves element in view
# param: element: TestUIElement
element.get_element().location_once_scrolled_into_view
page_title = "The GitHub Shop | Home"
driver.navigate_to("https://thegithubshop.com")
# Verify page title
if driver.get_driver().title != page_title:
driver.set_error("page title does not match expected")
driver.raise_errors()
# Take screenshot of shop page
driver.save_screenshot("website_shop.png")
# Move to track order button
move_to_element(e(driver, "css", "[title='Track my order']"))
# Navigate to track my order page
e(
driver, "css", "[title='Track my order']"
).wait_until_visible().click()
# Take screenshot of login page
driver.save_screenshot("login_page.png")
Example #2: using CSS selectors to locate elements
def test(driver: TestUIDriver):
# Example of locating elements using CSS selector
driver.navigate_to("https://www.bing.com")
# Wait 10 seconds until page is visible and take a screenshot
e(driver, "css", ".dimmer").wait_until_visible(seconds=10)
driver.save_screenshot("website_bing.png")
# Find search bar element and type "QA Processes" into it
e(driver, "css", "[type=search]").send_keys("QA Processes")
# Find search button and click it
e(driver, "css", "#search_icon").wait_until_visible(seconds=10).click()
# Wait 10 seconds until search results are visible and take a screenshot
e(
driver, "css", "[aria-label='Search Results']"
).wait_until_visible(seconds=10)
driver.save_screenshot("search_results.png")
Performing assertions
- JavaScript + Nightwatch.js
- Java + TestUI
- Python + Py-TestUI
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");
Example: using .assert and .verify
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")
.saveScreenshot("map.png");
}
Example: using TestUI element assertion methods
public void testUIWithLoadero() {
// Just some set-up so that we are in a page where we can try out all the
// assertion methods
open("https://www.bing.com")
.setElement(byCssSelector(".dimmer")).waitFor(10).untilIsVisible()
.setElement(byCssSelector("[type=search]")).sendKeys("QA Processes")
.setElement(byCssSelector("#search_icon")).click();
// Various assertion examples for the sake of demonstration
// Realistically, you wouldn't really want to do all of these in a row
// Assert an element's visibility
UIElement searchBar = E(byCssSelector("[type=search]"));
searchBar.shouldBe().visible();
// Assert that an element is enabled
searchBar.shouldBe().enabled();
// Assert that an element exists in the DOM at all
searchBar.shouldBe().exists();
// Assert that an element has exact text within it
UIElement anElementWithText = E(byCssSelector("#b-scopeListItem-images a"));
anElementWithText.shouldHave().exactText("IMAGES");
// Assert that an element CONTAINS the given text (but does not necessarily
// match it exactly)
anElementWithText.shouldHave().containText("MAGES");
// The above command also has a case insensitive option
anElementWithText.shouldHave().containNoCaseSensitiveText("mages");
// Assert that an element has the exact given value
searchBar.shouldHave().value("QA Processes");
// Assert that an element's attribute has the exact given value
searchBar.shouldHave().attribute("id").equalTo("sb_form_q");
searchBar.shouldHave().attribute("value").equalTo("QA Processes");
// Assert that an element has the given attribute AT ALL, regardless of its
// value
searchBar.shouldHave().theAttribute("maxlength");
// Any of the previous assertions can also be negated to achieve the exact
// opposite assertion
searchBar.shouldHave().not().theAttribute("minlength");
// Lastly, the above assertions are executed "in the moment".
// However, they can also be given a timer - to wait for a time period for the
// assertion to become true, if it is not immediately true already.
searchBar.waitFor(10).untilIsVisible();
searchBar.waitFor(10).untilIsEnabled();
searchBar.waitFor(10).untilExists();
anElementWithText.waitFor(10).untilHasText("IMAGES");
searchBar.waitFor(10).untilHasValue("QA Processes");
searchBar.waitFor(10).untilHasAttribute("maxlength");
// Negations are still an option
UIElement nonexistent = E(byCssSelector("i_do_not_exist"));
nonexistent.waitFor(10).untilNotExists();
}
You can find detailed descriptions and more examples in TestUI wiki.
Example: using Py-TestUI element assertion methods
def test(driver: TestUIDriver):
from testui.elements.testui_element import ElementException
driver.navigate_to("https://www.bing.com")
element = e(driver, "css", ".dimmer")
# The below code describes various ways to assert an element for the sake of
# demonstration. Realistically, you really should not be asserting the same
# element multiple times in a row.
# The .is_visible() command checks whether the element is visible and returns
# a Boolean value. If the element is not visible, there will NOT be an error
# and the script will continue.
if element.is_visible():
logger.log_debug("The element is visible!")
# The .is_visible_in() command checks whether the element becomes visible at
# any point within the specified time interval. A Boolean value is returned
# depending on the result and the script will continue.
if element.is_visible_in(10):
logger.log_debug("The element is visible!")
# The .visible_for() command asserts that the element REMAINS visible for all
# of the given time interval. If the element ceases to be visible within this
# interval, the script will fail.
element.visible_for(10)
# The .wait_until_visible() command is equivalent to .is_visible_in(), the
# difference being that the script will FAIL if the element does not appear
# within the given time period.
element.wait_until_visible(10)
# The .wait_until_attribute() command waits for the given time period for the
# specified attribute of the element to be equal to specified value. If these
# values do not match within the given time period, the script will fail.
element.wait_until_attribute("id", "", 10)
# The .wait_until_contains_attribute() commands is similar to
# .wait_until_attribute() but instead of checking for an exact match, the
# command checks whether the attribute CONTAINS the given value.
element.wait_until_contains_attribute("class", "dim", 10)
# The .wait_until_contains_sensitive_attribute() command is similar to
# .wait_until_contains_attribute(). However, this command is case insensitive,
# whereas the previous command is case sensitive. For example, if you were to
# provide "Dimmer" to "wait_until_contains_attribute(), it would fail."
element.wait_until_contains_sensitive_attribute("class", "Dimmer", 10)
# Any of the previous commands can also be prefixed with a .no() to achieve
# the opposite effect.
if element.no().is_visible_in(10):
logger.log_debug("PASS: The element did not show up within 10 seconds.")
else:
logger.log_debug(
"FAIL: The element appeared before 10 seconds had passed."
)
# Lastly, while only .is_visible_in() and .is_visible() allow the script to
# continue, it is possible NOT to fail the script when using the other
# commands as well. This can be done by handling ElementException. This way a
# fail will not occur and the script will continue.
try:
element = e(driver, "css", "i_do_not_exist")
element.wait_until_visible(10)
except ElementException:
logger.log_debug("The element was not visible! But we must continue...")
driver.save_screenshot(f"{element.locator}_not_found.png")
You can find detailed descriptions and more examples in Py-TestUI wiki.