Book Image

UI Testing with Puppeteer

By : Dario Kondratiuk
Book Image

UI Testing with Puppeteer

By: Dario Kondratiuk

Overview of this book

Puppeteer is an open source web automation library created by Google to perform tasks such as end-to-end testing, performance monitoring, and task automation with ease. Using real-world use cases, this book will take you on a pragmatic journey, helping you to learn Puppeteer and implement best practices to take your automation code to the next level! Starting with an introduction to headless browsers, this book will take you through the foundations of browser automation, showing you how far you can get using Puppeteer to automate Google Chrome and Mozilla Firefox. You’ll then learn the basics of end-to-end testing and understand how to create reliable tests. You’ll also get to grips with finding elements using CSS selectors and XPath expressions. As you progress through the chapters, the focus shifts to more advanced browser automation topics such as executing JavaScript code inside the browser. You’ll learn various use cases of Puppeteer, such as mobile devices or network speed testing, gauging your site’s performance, and using Puppeteer as a web scraping tool. By the end of this UI testing book, you’ll have learned how to make the most of Puppeteer’s API and be able to apply it in your real-world projects.
Table of Contents (12 chapters)

Finding elements using XPath

XPath is a language to query XML-like documents. Remember how we said that HTML was a relaxed kind of XML? This means that we could navigate through the DOM using some kind of XML query language such as XPath.

Before digging into XPath's selectors, if you want to try XPath queries, Chrome DevTools includes a set of functions you can use inside the developer tools Console tab (https://hardkoded.com/ui-testing-with-puppeteer/console). One of these functions is $x, which expects an XPath expression and returns an array of elements:

Testing XPath inside the Chrome Developer Tools

If you open the Console tab on any page, you can run $x('//*') to test the //* selector.

To better understand an XPath expression, you need to see your HTML as XML content. We are going to navigate this XML document from the very same root, the HTML attribute.

Select from the current node

Selector: //. This means "From the current...