SlideShare a Scribd company logo
Testing with Puppeteer - A Complete
Guide
In the earlier years of software development, testing was mostly done manually, which could be
a time-consuming and tedious process. These days, there are several tools that can help
automate the testing process. One such tool is Puppeteer, which allows you to control browsers
for testing purposes. This guide will take a really deep dive into what Puppeteer is and how it
can be used for web scraping and automation purposes.
What is Puppeteer, and what are its features
Puppeteer is a Node.js library that allows you to control Chrome or Chromium from the
command line. Puppeteer can be used for web scraping, automation, and testing purposes. This
guide will show you how to use Puppeteer for web scraping and automation purposes.
Puppeteer is a Node.js library that provides a high-level API to control Chromium or Chrome
over the DevTools Protocol. Puppeteer always runs headless by default but can be configured
to run full (non-headless) Chrome or Chromium.
Puppeteer offers APIs that allow you to control Chrome or Chromium programmatically. For
example, you can use Puppeteer to take screenshots, create PDFs, navigate pages, and more.
In addition, Puppeteer can be used for testing purposes. For example, you can use Puppeteer
to click on buttons and links, fill out forms, and assert that the expected results are displayed on
the page.
History of Puppeteer
Puppeteer was initially developed by Google to help developers automate their workflows. For
example, if you need to take a screenshot of a website, you can use Puppeteer to do it
automatically. In addition, Puppeteer can be used for web scraping and testing purposes.
Puppeteer was first released in 2017. Since then, it has been gaining constant popularity among
developers and QA professionals.
In 2018, Puppeteer was updated with a number of new features, including the ability to take
screenshots of web pages and generate PDFs.
Puppeteer is an open-source project, which means that anyone can contribute to it. This makes
Puppeteer an excellent tool for developers and QA professionals.
Why is Puppeteer a better testing platform than its peers?
Puppeteer is a great testing platform because it is easy to use, fast, and has a wide range of
features.
Puppeteer is easy to use because it is based on the DevTools Protocol, the same protocol used
by the Chrome Developer Tools. This means that if you are really familiar with the Chrome
Developer Tools, then you will ensure to get up and running with Puppeteer quickly. In addition,
Puppeteer has a number of helper functions that make everyday tasks, such as taking
screenshots and creating PDFs, easier to do.
Puppeteer is fast because it uses headless Chrome or Chromium. Headless browsers don't
have a UI, which means they are faster than traditional browsers. In addition, Puppeteer can run
multiple instances of Chrome or Chromium in parallel, which further speeds up the testing
process.
Puppeteer has a wide range of features that make it an excellent tool for web scraping and
automation purposes. For example, Puppeteer can be used to take screenshots, create PDFs,
navigate pages, and more. In addition, Puppeteer can be used for testing purposes. For
example, you can use Puppeteer to click on buttons and links, fill out forms, and assert that the
expected results are displayed on the page.
Difference between Puppeteer and other testing
platforms
Puppeteer is a great testing platform, but it is not the only one. There are a number of different
testing platforms that you can use for web scraping and automation purposes.
Difference between Puppeteer and WebKit/Blink
The main difference between Puppeteer and WebKit/Blink is that Puppeteer is a Node.js library
that provides a high-level API to control headless Chrome or Chromium, while WebKit/Blink is a
layout engine used by Safari and chromium browsers.
Difference between Puppeteer and Selenium
The main difference between Puppeteer and Selenium is that Puppeteer is a Node.js library that
communicates with Chrome or Chromium browsers directly over the debugging feature, while
Selenium manages browsers over a chromedriver. The chromedriver communicates with the
browsers.
Difference between Puppeteer and PhantomJS
The main difference between Puppeteer and PhantomJS is that Puppeteer is a Node.js library
that provides a high-level API to control headless Chrome or Chromium, while PhantomJS is a
headless web browser based on JavaScript and WebKit/Blink.
Difference between Puppeteer and Nightmare.JS
The main difference between Puppeteer and Nightmare is that Puppeteer is a Node.js library
that provides a high-level API to control headless Chrome or Chromium, while Nightmare is a
JavaScript library to render WebPage using Electron for automating browsers. Selenium can be
used with Puppeteer to automate browsers.
Difference between Puppeteer and Cypress
The main difference between Puppeteer and Cypress is that Puppeteer is a Node.js library that
provides a high-level API to control headless Chrome or Chromium, while Cypress is a
JavaScript automation framework which provides convenient methods for asynchronous testing.
How to install Puppeteer
Puppeteer is a Node.js library, which means it can be installed using npm, the Node package
manager. To install Puppeteer, run the following command:
npm install puppeteer
Once Puppeteer has been installed, you can use it in your Node.js scripts.
How to use Puppeteer for automation
Puppeteer can be used for automation purposes. In this section, we will be letting you know how
to use Puppeteer to automate the process of filling out a web form. We will be using the
example of filling out a form on HeadSpin sample code
https://github.com/headspinio/blog-samples running on your local.
First, you need to install Puppeteer using npm:
npm install puppeteer
Then, you need to prepare the sample server environment following “Setup” and “Run the local
server” sections in the
https://github.com/headspinio/blog-samples/tree/main/02-testing-with-puppeteer/README.md:
node server.js
Next, create a file named fill-form.js and add the following code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const timeout = 5000;
page.setDefaultTimeout(timeout);
try {
await page.goto("http://localhost:8000");
await page.waitForSelector(`#fname`, {timeout, visible: true});
await page.type(`#fname`, "");
await page.type(`#lname`, "");
await Promise.all([
page.click(`input[name="nameSubmit"]`),
page.waitForNavigation()
])
} catch (err) {
console.log(err);
} finally {
await browser.close();
}
})();
In the code above, we are using Puppeteer to fill out a form on the sample website that has a
first name input field and a last name input field. We are using the type() function to type text in
an input field. We are also using the click() function to click on a button and the
waitForNavigation() function to wait for the page to navigate to the next url before continuing.
The script saves a screenshot by page.screenshot().
To run the code, type the following command in 02-testing-with-puppeteer:
node test/fill-form.js
How to write and execute tests with Puppeteer
Puppeteer can be used for writing and executing tests. In this section, we will be letting you
know how to use Puppeteer to write a test that verifies that the title of a web page is correct. We
will be using the example of testing the title of the web page in the sample server.
First, you need to install Puppeteer using npm:
npm install puppeteer
Then, you need to prepare the sample server environment following “Setup”and “Run the local
server” sections in the
https://github.com/headspinio/blog-samples/tree/main/02-testing-with-puppeteer/README.md:
node server.js
Next, create a file named test.js and add the following code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const timeout = 5000;
page.setDefaultTimeout(timeout);
try {
await page.goto("http://localhost:8000");
await page.waitForSelector(`#fname`, {timeout, visible: true});
const title = await page.title();
console.log(title);
} catch (err) {
console.log(err);
} finally {
await browser.close();
}
})();
In the code above, we are using Puppeteer to test the title of the web page in the sample server.
We are using the title() function to get the title of the page, and then we are using the
console.log() function to print it out.
To run the code, type the following command:
node test/title.js
Using Puppeteer for testing web applications
Puppeteer can be used for testing web applications. In this section, we will show you how to use
Puppeteer to test the login functionality of a web application. We will be using the example of
testing the login functionality of the Facebook website.
First, you need to install Puppeteer using npm:
npm install puppeteer
Then, you need to prepare the sample server environment following “Setup” and “Run the local
server” sections in the
https://github.com/headspinio/blog-samples/tree/main/02-testing-with-puppeteer/README.md:
node server.js
Next, create a file named test-login.js and add the following code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const timeout = 5000;
page.setDefaultTimeout(timeout);
try {
await page.goto("http://localhost:8000");
await page.waitForSelector(`#fname`, {timeout, visible: true});
await page.type(`#email`, "your email");
await page.type(`#password`, "your password");
await page.screenshot({path: "./login.png", fullPage: true});
await Promise.all([
page.click(`input[name="loginSubmit"]`),
page.waitForNavigation()
])
const url = await page.url();
if (url !== `http://localhost:8000/login`) {
throw new Error(`The URL was not http://localhost:8000/login`);
}
console.log(url);
} catch (err) {
console.log(err);
} finally {
await browser.close();
}
})();
In the code above, we are using Puppeteer to test the login functionality of the sample website.
We are using the type() function to type text in an input field and the click() function to click on a
button. We are also using the waitForNavigation() function to wait for the page to navigate to the
next page before continuing.
To run the code, type the following command:
node test/login.js
How to automate tests with Puppeteer
Automating tests with Puppeteer can help speed up the testing process. This section will let you
know how to use Puppeteer to automate the test we created in the previous section.
First, create a file named test-login-automated.js and add the following code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const timeout = 5000;
page.setDefaultTimeout(timeout);
try {
await page.goto("http://localhost:8000");
await page.waitForSelector(`#fname`, {timeout, visible: true});
// Fill in email and password fields
await page.type(`#email`, "your email");
await page.type(`#password`, "your password");
await page.screenshot({path: "./login.png", fullPage: true});
await Promise.all([
// Click on login button
page.click(`input[name="loginSubmit"]`),
// Wait for page to navigate to the next page
page.waitForNavigation()
])
// Get url of the page
const url = await page.url();
if (url !== `http://localhost:8000/login`) {
throw new Error(`The URL was not http://localhost:8000/login`);
}
console.log(url);
} catch (err) {
console.log(err);
} finally {
// Close browser window
await browser.close();
}
})();
In the code above, we are using Puppeteer to automate the test we created in the previous
section. We are using the fill() function to type in input fields and the click() function to click on a
button. We are also using the waitForNavigation() function to wait for the page to navigate to the
next page.
To run the code, type the following command:
node test/login.js
Best practices for optimizing your tests with Puppeteer
You can follow some best practices to optimize your tests with Puppeteer. In this section, we will
be letting you know a list of the best practices for optimizing your tests.
●​ Minimizing the number of actions, you perform in each test is essential. This will help
improve the performance of your tests.
●​ It is vital to use the waitFor* functions wisely. Overusing these functions can slow down
your tests.
●​ It is crucial to parallelize your tests whenever possible. This will help improve the overall
performance of your tests.
●​ It is essential to use the headless mode when running your tests. This will help improve
the performance of your tests.
●​ Always keep your test code up to date with the latest changes in Puppeteer. This will
ensure that your tests are running correctly.
●​ Use the supported Node.js versions by the core team when running your tests. This will
ensure that your tests are running correctly.
●​ Make sure to use a properly configured test runner when running your tests. This will
ensure that your tests are running correctly.
●​ Do not use Puppeteer for web scraping purposes. This is against the Terms of Service of
many websites. Do not use Puppeteer for illegal purposes.
●​ Make sure to read the Puppeteer documentation carefully. This will help you understand
how to use Puppeteer correctly. Make sure to read the headless-chrome docs as well.
Puppeteer is a powerful tool for testing web pages and automating browsers. It is an essential
tool for developers and QA professionals. By following the above-written best practices, you can
optimize your tests and improve the overall performance of your testing process.
HeadSpin Puppeteer Integration
HeadSpin is a mobile user experience testing platform that allows you to test your web pages
on real devices. It provides several features, such as simulating different network conditions and
capturing video recordings of your tests.
HeadSpin platform uses Puppeteer to provide accurate and up-to-date test coverage for web
pages. This helps ensure that your tests are running correctly.
HeadSpin platform integrates with Puppeteer to provide a complete testing solution for web
pages. HeadSpin offers a wide range of features and tools to help you test your web pages. It is
easy to use, and this makes it an essential tool for developers and QA professionals.
Examples of real-world tests using Puppeteer
In this section, we are going to let you know some examples of real-world tests that have been
created using Puppeteer.
Example 1
The first example is a login test for a web page. This test will fill in the username and password
fields and click on the login button. Then, it will wait for the page to navigate to the next page.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com/login');
// fill in the username and password fields
await page.type('#username', 'testuser');
await page.type('#password', 'testpass');
// click on the login button
await page.click('#login-button');
// wait for the page to navigate to the next page
await page.waitForNavigation();
await browser.close();
})();
Example 2 - 4
The second example is if a web page contains the correct url. This test will navigate to the
HeadSpin GitHub top and checks if the url is correct. If the url is not right, the test will fail.
The third example is if a web page contains a specific element, if the page has an element with
the id "your-repos-filter". If the placeholder of the element is not expected, the test will fail.
The fifth example is if a web page contains a specific image. This test will check if the page
contains an image with the src "avatars.githubusercontent.com". If the image is not found, the
test will fail.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
try {
const timeout = 5000;
page.setDefaultTimeout(timeout);
await page.goto("https://github.com/headspinio");
const url = await page.url();
if (url !== `https://github.com/headspinio`) {
throw new Error(`The URL was not https://github.com/headspinio`);
}
await page.screenshot({path: "./github-headspinio.png", fullPage: true});
const repoTab = await page.$(`a[href$="/orgs/headspinio/repositories"]`);
await repoTab.click();
await page.waitForNavigation();
const placeholder = await page.$eval(`[id="your-repos-filter"]`, el =>
el.getAttribute('placeholder'))
if (placeholder !== ”Find a repository…”) {
throw new Error(`The search placeholder was not 'Find a repository…'. Actual:
${placeholder}`);
}
await page.screenshot({path: "./github-headspinio-repos.png", fullPage: true});
const imgSrc = await page.$eval(`img[alt="@headspinio"]`, async (el) => await
el.getAttribute('src'));
if (!imgSrc.startsWith("https://avatars.githubusercontent.com")) {
throw new Error(`The image was not an avatar image`);
}
} catch (err) {
console.log(err);
} finally {
await browser.close();
}
})();
These are just some of the large sets of examples of tests that can be created using Puppeteer.
There are further possibilities, and we encourage you to explore them.
The sample code “test/github-headspinio.js” contains an example to run the test on a HeadSpin
browser.
Conclusion
Puppeteer is a powerful tool for testing web pages and automating browsers. It is an essential
tool for developers and QA professionals. In this guide, we have let you know how to use
Puppeteer for testing purposes. We have also listed some of the best practices for optimizing
your tests with Puppeteer. By following the above-written best practices, you can optimize your
tests and improve the overall performance of your testing process.
Article Source:
This article was originally published on:
https://www.headspin.io/blog/testing-with-puppeteer-a-complete-guide

More Related Content

PDF
Testing with Puppeteer - A Complete Guide.pdf
PPTX
Puppeteer - Headless Chrome Node API
PPTX
Puppeteer
PDF
vodQA Pune (2019) - Browser automation using dev tools
PDF
Playwright Testing Guide for QA Engineers.pdf
PDF
Getting Started with Playwright: A Beginner-Friendly Introduction & Setup Guide
PPTX
APIs for Browser Automation (MoT Meetup 2024)
PPTX
Puppeteer (JavaScript library for UI testing)
Testing with Puppeteer - A Complete Guide.pdf
Puppeteer - Headless Chrome Node API
Puppeteer
vodQA Pune (2019) - Browser automation using dev tools
Playwright Testing Guide for QA Engineers.pdf
Getting Started with Playwright: A Beginner-Friendly Introduction & Setup Guide
APIs for Browser Automation (MoT Meetup 2024)
Puppeteer (JavaScript library for UI testing)

Similar to Testing with Puppeteer - A Complete Guide.pdf (20)

ODP
Improving code quality using CI
PDF
Intro to Puppeteer
PDF
Playwright vs. Puppeteer : Choosing the Right Browser Automation Library.pdf
PDF
10 Best Puppeteer Alternatives in Web Scraping.pdf
PPTX
How to Develop Progressive Web Apps in Flutter – Step by Step Guide.pptx
PPTX
Technical Tips: Visual Regression Testing and Environment Comparison with Bac...
PDF
Python Online Compiler
PDF
Banquet 42
PDF
夜宴42期《Gadgets》
PDF
Using HttpWatch Plug-in with Selenium Automation in Java
PPT
Introduction to python scrapping
PPTX
Selenium.pptx
PDF
Front End Development for Back End Developers - vJUG24 2017
PPTX
Performance Metrics in a Day with Selenium
PPTX
How to start ui automation in 15 mins with Puppeteer
PDF
Puppeteer: Getting Started
ODP
Mangling
PPTX
Hacking the browser with puppeteer sharp .NET conf AR 2018
PDF
Puppeteer - A web scraping & UI Testing Tool
PDF
Headless browser a stepping stone towards developing smarter web applicatio...
Improving code quality using CI
Intro to Puppeteer
Playwright vs. Puppeteer : Choosing the Right Browser Automation Library.pdf
10 Best Puppeteer Alternatives in Web Scraping.pdf
How to Develop Progressive Web Apps in Flutter – Step by Step Guide.pptx
Technical Tips: Visual Regression Testing and Environment Comparison with Bac...
Python Online Compiler
Banquet 42
夜宴42期《Gadgets》
Using HttpWatch Plug-in with Selenium Automation in Java
Introduction to python scrapping
Selenium.pptx
Front End Development for Back End Developers - vJUG24 2017
Performance Metrics in a Day with Selenium
How to start ui automation in 15 mins with Puppeteer
Puppeteer: Getting Started
Mangling
Hacking the browser with puppeteer sharp .NET conf AR 2018
Puppeteer - A web scraping & UI Testing Tool
Headless browser a stepping stone towards developing smarter web applicatio...
Ad

More from flufftailshop (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Test Reporting in Software Testing_ A Comprehensive Overview.pdf
PDF
How Does Continuous Testing Accelerate DevOps.pdf
PDF
UI (User Interface Testing) - A Complete Guide.pdf
PDF
The Significance of Software Compliance Testing.pdf
PDF
14 Best Mobile App Test Automation Tools and Framework.pdf
PDF
Top 8 Automated Android App Testing Tools in 2025.pdf
PDF
What is Visual Regression Testing Advantages, Process and Approaches.pdf
PDF
6 Popular Test Automation Tools For React Native App.pdf
PDF
Unlocking the Potential of Flutter App Testing_ A Comprehensive Guide-1.pdf
PDF
How to Improve App Performance in 2025.pdf
PDF
Using XPath in Selenium - All you need to know.pdf
PDF
A Complete Guide to Web Apps Testing.pdf
PDF
Non-Functional Testing Guide_ Exploring Its Types, Importance and Tools.pdf
PDF
How Cloud Performance Testing Offers a Cost Advantage Amidst The Economic Rec...
PDF
HeadSpin’s Guide to Leveraging Network-based App Observability.pdf
PDF
Maximize Your Testing Efficiency_ 4 Essential Tips for Software Test Manageme...
PDF
Shift-Left Testing - Everything You Need to Know About.pdf
PDF
Why Should Telcos Focus on Roaming Testing.pdf
PDF
OTT Testing Tutorial_ Benefits, Challenges and Their Solutions.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Test Reporting in Software Testing_ A Comprehensive Overview.pdf
How Does Continuous Testing Accelerate DevOps.pdf
UI (User Interface Testing) - A Complete Guide.pdf
The Significance of Software Compliance Testing.pdf
14 Best Mobile App Test Automation Tools and Framework.pdf
Top 8 Automated Android App Testing Tools in 2025.pdf
What is Visual Regression Testing Advantages, Process and Approaches.pdf
6 Popular Test Automation Tools For React Native App.pdf
Unlocking the Potential of Flutter App Testing_ A Comprehensive Guide-1.pdf
How to Improve App Performance in 2025.pdf
Using XPath in Selenium - All you need to know.pdf
A Complete Guide to Web Apps Testing.pdf
Non-Functional Testing Guide_ Exploring Its Types, Importance and Tools.pdf
How Cloud Performance Testing Offers a Cost Advantage Amidst The Economic Rec...
HeadSpin’s Guide to Leveraging Network-based App Observability.pdf
Maximize Your Testing Efficiency_ 4 Essential Tips for Software Test Manageme...
Shift-Left Testing - Everything You Need to Know About.pdf
Why Should Telcos Focus on Roaming Testing.pdf
OTT Testing Tutorial_ Benefits, Challenges and Their Solutions.pdf
Ad

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Cloud computing and distributed systems.
PPTX
A Presentation on Artificial Intelligence
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation theory and applications.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
Big Data Technologies - Introduction.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Digital-Transformation-Roadmap-for-Companies.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
“AI and Expert System Decision Support & Business Intelligence Systems”
Per capita expenditure prediction using model stacking based on satellite ima...
Electronic commerce courselecture one. Pdf
Encapsulation_ Review paper, used for researhc scholars
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
20250228 LYD VKU AI Blended-Learning.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Cloud computing and distributed systems.
A Presentation on Artificial Intelligence
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation theory and applications.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Big Data Technologies - Introduction.pptx

Testing with Puppeteer - A Complete Guide.pdf

  • 1. Testing with Puppeteer - A Complete Guide In the earlier years of software development, testing was mostly done manually, which could be a time-consuming and tedious process. These days, there are several tools that can help automate the testing process. One such tool is Puppeteer, which allows you to control browsers for testing purposes. This guide will take a really deep dive into what Puppeteer is and how it can be used for web scraping and automation purposes. What is Puppeteer, and what are its features Puppeteer is a Node.js library that allows you to control Chrome or Chromium from the command line. Puppeteer can be used for web scraping, automation, and testing purposes. This guide will show you how to use Puppeteer for web scraping and automation purposes. Puppeteer is a Node.js library that provides a high-level API to control Chromium or Chrome over the DevTools Protocol. Puppeteer always runs headless by default but can be configured to run full (non-headless) Chrome or Chromium. Puppeteer offers APIs that allow you to control Chrome or Chromium programmatically. For example, you can use Puppeteer to take screenshots, create PDFs, navigate pages, and more. In addition, Puppeteer can be used for testing purposes. For example, you can use Puppeteer
  • 2. to click on buttons and links, fill out forms, and assert that the expected results are displayed on the page. History of Puppeteer Puppeteer was initially developed by Google to help developers automate their workflows. For example, if you need to take a screenshot of a website, you can use Puppeteer to do it automatically. In addition, Puppeteer can be used for web scraping and testing purposes. Puppeteer was first released in 2017. Since then, it has been gaining constant popularity among developers and QA professionals. In 2018, Puppeteer was updated with a number of new features, including the ability to take screenshots of web pages and generate PDFs. Puppeteer is an open-source project, which means that anyone can contribute to it. This makes Puppeteer an excellent tool for developers and QA professionals. Why is Puppeteer a better testing platform than its peers? Puppeteer is a great testing platform because it is easy to use, fast, and has a wide range of features. Puppeteer is easy to use because it is based on the DevTools Protocol, the same protocol used by the Chrome Developer Tools. This means that if you are really familiar with the Chrome Developer Tools, then you will ensure to get up and running with Puppeteer quickly. In addition, Puppeteer has a number of helper functions that make everyday tasks, such as taking screenshots and creating PDFs, easier to do. Puppeteer is fast because it uses headless Chrome or Chromium. Headless browsers don't have a UI, which means they are faster than traditional browsers. In addition, Puppeteer can run multiple instances of Chrome or Chromium in parallel, which further speeds up the testing process. Puppeteer has a wide range of features that make it an excellent tool for web scraping and automation purposes. For example, Puppeteer can be used to take screenshots, create PDFs, navigate pages, and more. In addition, Puppeteer can be used for testing purposes. For example, you can use Puppeteer to click on buttons and links, fill out forms, and assert that the expected results are displayed on the page. Difference between Puppeteer and other testing platforms
  • 3. Puppeteer is a great testing platform, but it is not the only one. There are a number of different testing platforms that you can use for web scraping and automation purposes. Difference between Puppeteer and WebKit/Blink The main difference between Puppeteer and WebKit/Blink is that Puppeteer is a Node.js library that provides a high-level API to control headless Chrome or Chromium, while WebKit/Blink is a layout engine used by Safari and chromium browsers. Difference between Puppeteer and Selenium The main difference between Puppeteer and Selenium is that Puppeteer is a Node.js library that communicates with Chrome or Chromium browsers directly over the debugging feature, while Selenium manages browsers over a chromedriver. The chromedriver communicates with the browsers. Difference between Puppeteer and PhantomJS The main difference between Puppeteer and PhantomJS is that Puppeteer is a Node.js library that provides a high-level API to control headless Chrome or Chromium, while PhantomJS is a headless web browser based on JavaScript and WebKit/Blink. Difference between Puppeteer and Nightmare.JS The main difference between Puppeteer and Nightmare is that Puppeteer is a Node.js library that provides a high-level API to control headless Chrome or Chromium, while Nightmare is a JavaScript library to render WebPage using Electron for automating browsers. Selenium can be used with Puppeteer to automate browsers. Difference between Puppeteer and Cypress The main difference between Puppeteer and Cypress is that Puppeteer is a Node.js library that provides a high-level API to control headless Chrome or Chromium, while Cypress is a JavaScript automation framework which provides convenient methods for asynchronous testing. How to install Puppeteer Puppeteer is a Node.js library, which means it can be installed using npm, the Node package manager. To install Puppeteer, run the following command: npm install puppeteer
  • 4. Once Puppeteer has been installed, you can use it in your Node.js scripts. How to use Puppeteer for automation Puppeteer can be used for automation purposes. In this section, we will be letting you know how to use Puppeteer to automate the process of filling out a web form. We will be using the example of filling out a form on HeadSpin sample code https://github.com/headspinio/blog-samples running on your local. First, you need to install Puppeteer using npm: npm install puppeteer Then, you need to prepare the sample server environment following “Setup” and “Run the local server” sections in the https://github.com/headspinio/blog-samples/tree/main/02-testing-with-puppeteer/README.md: node server.js Next, create a file named fill-form.js and add the following code: const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); const timeout = 5000; page.setDefaultTimeout(timeout); try { await page.goto("http://localhost:8000"); await page.waitForSelector(`#fname`, {timeout, visible: true}); await page.type(`#fname`, ""); await page.type(`#lname`, ""); await Promise.all([ page.click(`input[name="nameSubmit"]`), page.waitForNavigation() ]) } catch (err) {
  • 5. console.log(err); } finally { await browser.close(); } })(); In the code above, we are using Puppeteer to fill out a form on the sample website that has a first name input field and a last name input field. We are using the type() function to type text in an input field. We are also using the click() function to click on a button and the waitForNavigation() function to wait for the page to navigate to the next url before continuing. The script saves a screenshot by page.screenshot(). To run the code, type the following command in 02-testing-with-puppeteer: node test/fill-form.js How to write and execute tests with Puppeteer Puppeteer can be used for writing and executing tests. In this section, we will be letting you know how to use Puppeteer to write a test that verifies that the title of a web page is correct. We will be using the example of testing the title of the web page in the sample server. First, you need to install Puppeteer using npm: npm install puppeteer Then, you need to prepare the sample server environment following “Setup”and “Run the local server” sections in the https://github.com/headspinio/blog-samples/tree/main/02-testing-with-puppeteer/README.md: node server.js Next, create a file named test.js and add the following code: const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage();
  • 6. const timeout = 5000; page.setDefaultTimeout(timeout); try { await page.goto("http://localhost:8000"); await page.waitForSelector(`#fname`, {timeout, visible: true}); const title = await page.title(); console.log(title); } catch (err) { console.log(err); } finally { await browser.close(); } })(); In the code above, we are using Puppeteer to test the title of the web page in the sample server. We are using the title() function to get the title of the page, and then we are using the console.log() function to print it out. To run the code, type the following command: node test/title.js Using Puppeteer for testing web applications Puppeteer can be used for testing web applications. In this section, we will show you how to use Puppeteer to test the login functionality of a web application. We will be using the example of testing the login functionality of the Facebook website. First, you need to install Puppeteer using npm: npm install puppeteer Then, you need to prepare the sample server environment following “Setup” and “Run the local server” sections in the https://github.com/headspinio/blog-samples/tree/main/02-testing-with-puppeteer/README.md: node server.js
  • 7. Next, create a file named test-login.js and add the following code: const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); const timeout = 5000; page.setDefaultTimeout(timeout); try { await page.goto("http://localhost:8000"); await page.waitForSelector(`#fname`, {timeout, visible: true}); await page.type(`#email`, "your email"); await page.type(`#password`, "your password"); await page.screenshot({path: "./login.png", fullPage: true}); await Promise.all([ page.click(`input[name="loginSubmit"]`), page.waitForNavigation() ]) const url = await page.url(); if (url !== `http://localhost:8000/login`) { throw new Error(`The URL was not http://localhost:8000/login`); } console.log(url); } catch (err) { console.log(err); } finally { await browser.close(); } })(); In the code above, we are using Puppeteer to test the login functionality of the sample website. We are using the type() function to type text in an input field and the click() function to click on a button. We are also using the waitForNavigation() function to wait for the page to navigate to the next page before continuing. To run the code, type the following command:
  • 8. node test/login.js How to automate tests with Puppeteer Automating tests with Puppeteer can help speed up the testing process. This section will let you know how to use Puppeteer to automate the test we created in the previous section. First, create a file named test-login-automated.js and add the following code: const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); const timeout = 5000; page.setDefaultTimeout(timeout); try { await page.goto("http://localhost:8000"); await page.waitForSelector(`#fname`, {timeout, visible: true}); // Fill in email and password fields await page.type(`#email`, "your email"); await page.type(`#password`, "your password"); await page.screenshot({path: "./login.png", fullPage: true}); await Promise.all([ // Click on login button page.click(`input[name="loginSubmit"]`), // Wait for page to navigate to the next page page.waitForNavigation() ]) // Get url of the page const url = await page.url(); if (url !== `http://localhost:8000/login`) { throw new Error(`The URL was not http://localhost:8000/login`); } console.log(url); } catch (err) { console.log(err);
  • 9. } finally { // Close browser window await browser.close(); } })(); In the code above, we are using Puppeteer to automate the test we created in the previous section. We are using the fill() function to type in input fields and the click() function to click on a button. We are also using the waitForNavigation() function to wait for the page to navigate to the next page. To run the code, type the following command: node test/login.js Best practices for optimizing your tests with Puppeteer You can follow some best practices to optimize your tests with Puppeteer. In this section, we will be letting you know a list of the best practices for optimizing your tests. ●​ Minimizing the number of actions, you perform in each test is essential. This will help improve the performance of your tests. ●​ It is vital to use the waitFor* functions wisely. Overusing these functions can slow down your tests. ●​ It is crucial to parallelize your tests whenever possible. This will help improve the overall performance of your tests. ●​ It is essential to use the headless mode when running your tests. This will help improve the performance of your tests. ●​ Always keep your test code up to date with the latest changes in Puppeteer. This will ensure that your tests are running correctly. ●​ Use the supported Node.js versions by the core team when running your tests. This will ensure that your tests are running correctly. ●​ Make sure to use a properly configured test runner when running your tests. This will ensure that your tests are running correctly. ●​ Do not use Puppeteer for web scraping purposes. This is against the Terms of Service of many websites. Do not use Puppeteer for illegal purposes. ●​ Make sure to read the Puppeteer documentation carefully. This will help you understand how to use Puppeteer correctly. Make sure to read the headless-chrome docs as well.
  • 10. Puppeteer is a powerful tool for testing web pages and automating browsers. It is an essential tool for developers and QA professionals. By following the above-written best practices, you can optimize your tests and improve the overall performance of your testing process. HeadSpin Puppeteer Integration HeadSpin is a mobile user experience testing platform that allows you to test your web pages on real devices. It provides several features, such as simulating different network conditions and capturing video recordings of your tests. HeadSpin platform uses Puppeteer to provide accurate and up-to-date test coverage for web pages. This helps ensure that your tests are running correctly. HeadSpin platform integrates with Puppeteer to provide a complete testing solution for web pages. HeadSpin offers a wide range of features and tools to help you test your web pages. It is easy to use, and this makes it an essential tool for developers and QA professionals. Examples of real-world tests using Puppeteer In this section, we are going to let you know some examples of real-world tests that have been created using Puppeteer. Example 1 The first example is a login test for a web page. This test will fill in the username and password fields and click on the login button. Then, it will wait for the page to navigate to the next page. const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com/login'); // fill in the username and password fields await page.type('#username', 'testuser'); await page.type('#password', 'testpass'); // click on the login button await page.click('#login-button'); // wait for the page to navigate to the next page await page.waitForNavigation();
  • 11. await browser.close(); })(); Example 2 - 4 The second example is if a web page contains the correct url. This test will navigate to the HeadSpin GitHub top and checks if the url is correct. If the url is not right, the test will fail. The third example is if a web page contains a specific element, if the page has an element with the id "your-repos-filter". If the placeholder of the element is not expected, the test will fail. The fifth example is if a web page contains a specific image. This test will check if the page contains an image with the src "avatars.githubusercontent.com". If the image is not found, the test will fail. const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); try { const timeout = 5000; page.setDefaultTimeout(timeout); await page.goto("https://github.com/headspinio"); const url = await page.url(); if (url !== `https://github.com/headspinio`) { throw new Error(`The URL was not https://github.com/headspinio`); } await page.screenshot({path: "./github-headspinio.png", fullPage: true}); const repoTab = await page.$(`a[href$="/orgs/headspinio/repositories"]`); await repoTab.click(); await page.waitForNavigation(); const placeholder = await page.$eval(`[id="your-repos-filter"]`, el => el.getAttribute('placeholder')) if (placeholder !== ”Find a repository…”) { throw new Error(`The search placeholder was not 'Find a repository…'. Actual: ${placeholder}`); }
  • 12. await page.screenshot({path: "./github-headspinio-repos.png", fullPage: true}); const imgSrc = await page.$eval(`img[alt="@headspinio"]`, async (el) => await el.getAttribute('src')); if (!imgSrc.startsWith("https://avatars.githubusercontent.com")) { throw new Error(`The image was not an avatar image`); } } catch (err) { console.log(err); } finally { await browser.close(); } })(); These are just some of the large sets of examples of tests that can be created using Puppeteer. There are further possibilities, and we encourage you to explore them. The sample code “test/github-headspinio.js” contains an example to run the test on a HeadSpin browser. Conclusion Puppeteer is a powerful tool for testing web pages and automating browsers. It is an essential tool for developers and QA professionals. In this guide, we have let you know how to use Puppeteer for testing purposes. We have also listed some of the best practices for optimizing your tests with Puppeteer. By following the above-written best practices, you can optimize your tests and improve the overall performance of your testing process. Article Source: This article was originally published on: https://www.headspin.io/blog/testing-with-puppeteer-a-complete-guide