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)

Executing JavaScript code

The first question you might ask is: "Why would I need to run JavaScript code? Shouldn't Puppeteer give me all the APIs I need?" Well, yes and no.

Before getting into the different possible use cases, let's see how this feature works.

Variable scopes in JavaScript

One thing that makes JavaScript so flexible is that functions are first-class citizens. You can declare functions, assign them to variables, and pass them as an argument. You could even return functions from other functions, like in this example:

function getFunc() {
    let word = 'world'; 
    return function() {
        console.log('Hello ' + word);
    }
}
getFunc()();

That code is pretty fun. getFunc returns another function. When we do getFunc()(), we are calling the function returned by getFunc.

This piece of code will print 'Hello...