A quick look at Intern’s findByXpath

By on June 14, 2016 9:32 am

Intern Logo

Intern‘s Leadfoot API makes it easier to author functional tests in JavaScript. One of the fundamental concepts for authoring functional tests is to access an element within a page to test it.

While most developers are familiar with CSS selectors, this is not always the most efficient mechanism for referencing a particular element in a page.

findByXpath

XPath is a technology that is often overlooked by developers because of the perception that all things XML are overly complex. That said, XPath selectors can be a very powerful and flexible approach for finding an element.

Where findByLinkText only finds links, and findByCssSelector is limited to the capabilities of the CSS engine in the target browser, findByXpath can do much more.

For example, given a simple DOM structure like this:

<dl>
  <dt id="hw">Hello, world</dt>
  <dd>A common greeting</dd>
</dl>

It is possible to find elements in all sorts of different ways:

  • Find the dt element by its text content: findByXpath('//[.="Hello, world"]')
  • Find the parent of the element with id="hw": findByXpath('//[@id="hw"]/..')
  • Find the preceding dt element of the dd element: findByXpath('//dd/preceding-sibling::dt[1]')

These are just some very simple examples of the sorts of complex element selection you can only perform using XPath. The next time you need to find an element with no simple identifier, an XPath selector could be the solution.


Learning more

Support Logo

Get help from SitePen Support, our fast and efficient solutions to development problems of any size.

Workshops Logo

SitePen workshops are a fun, hands-on way to keep up with JavaScript best practices. Register for an online workshop, today!

Let's Talk! Logo

Let’s talk about how we can help your organization improve their approach to automated testing.

Contact Us Logo

Have a question? We’re here to help! Get in touch and let’s see how we can work together.