Waltir
By: Waltir

Using Xpath Selectors In Nightwatch JS

Cover Image for Using Xpath Selectors In Nightwatch JS

XPath (XML Path Language) is a language used to navigate and locate elements in an XML document, including (X)HTML documents. It is commonly used in web scraping and automated testing to locate elements on a web page. Nightwatch.js, a popular automated testing framework, provides support for XPath selectors, allowing developers to easily locate and interact with elements on a web page.

Simple XPath selectors are the most basic form of XPath and are used to locate elements by their tag name, attributes, and attribute values. For example, the following XPath selector will locate all

elements on a web page:

//div

The // at the beginning of the selector is called the "descendant-or-self" axis, which means that it will search for the

elements anywhere in the document.

A more specific selector can be used to locate an element by its attribute and value. For example, the following XPath selector will locate the first element with a name attribute of "username":

//input[@name='username']

Advanced XPath selectors, also known as "location path", allow developers to locate elements based on their position in the document. These selectors use different axes, such as "child", "parent", and "sibling", to navigate the document.

For example, the following XPath selector will locate the first element that is a child of the first element:

//tr[1]/td[1]

The [1] at the end of each element in the selector is called the "predicate", which is used to select a specific element based on its position. In this example, it is selecting the first and elements.

In Nightwatch.js, you can use the .useXpath() command to switch to using XPath selectors. Once switched, you can use the .expect.element() command with the XPath selector to check if the element is present, visible or enabled. The .click() command can be used to interact with an element that is selected using the xpath.

For example, the following code will check for an element with an ID of "username" and click on it:

browser
  .useXpath()
  .expect.element("//input[@id='username']").to.be.visible
  .click("//input[@id='username']")
  .useCss()

The .useCss() command is used to switch back to using CSS selectors.

XPath is a powerful tool for navigating and selecting elements in XML and HTML documents. It is widely used in web scraping, testing, and data extraction. Here are some best practices for using XPath to make your queries more efficient and reliable.

  • Use the most specific path possible: When selecting elements, use the most specific path possible to minimize the number of elements that need to be searched through. For example, instead of using "//div", use "//div[@class='my-class']".

  • Avoid using the "//" operator: The "//" operator searches the entire document for a matching element, which can be slow and resource-intensive. Instead, use the "/" operator to search only within the current context.

  • Use the "text()" function to select text nodes: To select the text content of an element, use the "text()" function. For example, "//div/text()" will select the text content of all div elements.

  • Use predicates to filter elements: Predicates are conditions that are applied to elements to filter them. For example, "//div[@class='my-class'][2]" will select the second div element with the class "my-class".

  • Use the "starts-with" and "contains" functions: The "starts-with" and "contains" functions can be used to match elements based on their attribute values. For example, "//div[starts-with(@class, 'my-class')]" will select all div elements that have a class attribute that starts with "my-class".

  • Use the "or" operator to combine multiple conditions: The "or" operator can be used to combine multiple conditions. For example, "//div[@class='my-class' or @id='my-id']" will select all div elements that have a class of "my-class" or an id of "my-id".

  • Avoid using the "" operator: The "" operator matches all elements, which can be slow and resource-intensive. Instead, use a more specific path.

  • Test your XPath expressions in browser developer tools: Most web browsers have built-in developer tools that allow you to test XPath expressions on a web page. This can be a great way to debug and optimize your queries.

Example:

For example, let's say you have the following XML document:

<books>
    <book>
        <title>The Catcher in the Rye</title>
        <author>J.D. Salinger</author>
        <year>1951</year>
    </book>
    <book>
        <title>To Kill a Mockingbird</title>
        <author>Harper Lee</author>
        <year>1960</year>
    </book>
    <book>
        <title>1984</title>
        <author>George Orwell</author>
        <year>1949</year>
    </book>
</books>

To select the title of all books written before 1960, you could use the following XPath expression:

//book[year<1960]/title/text()

This will select the text content of the title element for all book elements where the year is less than 1960.

Overall, XPath is a powerful tool for working with XML and HTML documents, but it's important to use best practices to make your queries.

In conclusion, XPath selectors are a powerful tool for locating elements on a web page and can be used in Nightwatch.js automated tests to interact with those elements. Simple selectors can be used to locate elements by their tag name, attributes, and attribute values, while advanced selectors can be used to locate elements based on their position in the document. With the use of xpath, you can make your Nightwatch.js automated tests more robust and reliable.

Additional Nightwatch.JS Xpath Test Example

module.exports = {
  'Search Google for Nightwatch': function (browser) {
    browser.url('https://www.google.com')
      .waitForElementVisible('body', 1000)
      .setValue('input[type=text]', 'Nightwatch')
      .click('input[type=submit]')
      .pause(1000)
      .assert.titleContains('Nightwatch')
      .elements('xpath', '//div[@class="g"]', function (result) {
        browser.assert.equal(result.value.length, 10, 'Expected 10 search results');
      })
      .elements('css selector', 'h3 > a', function (result) {
        browser.assert.equal(result.value.length, 10, 'Expected 10 search result links');
      })
      .end();
  }
};

More Posts

Cover Image for Blocking Ad Traffic In Nightwatch JS
Blocking Ad Traffic In Nightwatch JS
Waltir
By: Waltir

Example showing how you can block unwanted ad traffic in your Nightwatch JS tests....

Cover Image for Blocking Ad Traffic In Cypress
Blocking Ad Traffic In Cypress
Waltir
By: Waltir

Example showing how you can block unwanted ad traffic in your Cypress tests....

Cover Image for Three Ways To Resize The Browser In Nightwatch
Three Ways To Resize The Browser In Nightwatch
Waltir
By: Waltir

Outlining the three different ways to resize the browser in Nightwatch JS with examples....

Cover Image for Happy Path VS Sad Path Testing
Happy Path VS Sad Path Testing
Waltir
By: Waltir

As a test engineer it is crucial that both happy path and sad path use cases have been considered and fully tested...