Puppeteer Automation Testing – An Excellent Guide of Puppeteer Tutorial 6

Puppeteer Automation Testing - Feature Image

The Puppeteer is a node js library based framework which is available as open-source. It can be used for web scraping tools. It’s also used for test automation tools as well. Now-a-days, the usage of Puppeteer is getting increased rapidly in the automated software testing space. Basic knowledge of command line, Javascript, and HTML DOM structure is required to understand puppeteer tutorial. The entire tutorial is segregated into the below articles. 

Puppeteer Tutorial

Tosca Tutorial #1: Puppeteer Overview

Tosca Tutorial #2: Puppeteer Environment Variables

Tosca Tutorial #3: Puppeteer Web Scraping and Puppeteer Test Automation Overview

Tosca Tutorial #4: Install Puppeteer

Tosca Tutorial #5: Sample Puppeteer Project

Tosca Tutorial #6: Puppeteer Automation Testing

In this “Puppeteer Automation Testing” tutorial, we will explain the detailed steps for Puppeteer Automation from the beginning. Below features will be explained to understand Puppeteer Automation testing from scratch –

· Install Puppeteer

· Launch Web Application

· Identify object properties from the Chrome Browser

· Form Submission steps – Enter text, Click event, Verification

· Screenshot capture

· Execute scripts for Puppeteer Automation

Puppeteer Automation

Testing is required to ensure the quality of software products. There are multiple levels of testing defined in the software development processes. To test the functionalities of a software, can be done manually or through automated process. The main purposes of automated software testing are –

  • Fast test execution cycle.
  • Avoid the chances of human errors.
  • Reduce the test execution timing.
  • Reduce the release cycle time.
  • Cove more functionality with out compromising with quality.
  • Multiple execution can be done parallelly.

 Puppeteer is a javascript based Node library that gives a high-level application interface(API) to control the Chrome web browser over the Chrome DevTools protocol. Most of the manual operations performed in the Chrome browser can be automated using Puppeteer. So, the Puppeteer is a good choice for unit testing on web applications fast and easier way. 

Puppeteer Automation Testing Approach:

The steps involved with Puppeteer Automation Testing are explained below – 

Step1# Identify Functional Test Scenario:

We will show the step by step approach to performing Puppeteer automation for the below scenario – 

· Launch the Web Browser.

· Invoke Amazon Web application.

  • Search for the book “Testing Book”.
  • Add the book into the cart from the result.
  • Open cart and check if the book is available in the cart.
  • Capture screen and close the browser.

Step2# Install Puppeteer and Create Test Case:

Create an empty javascript file as “sample_script.js” in a specific folder. Here, we will consider the root folder as SampleProject. To install Puppeteer, we will use the command – “npm install puppeteer”. The installation procedure takes some time based on the network speed. It will download approximately 350MBs of data. After installation, the node_modules folder, which contains different puppeteer components and package-lock.json file, will be created to the sample Puppeteer project root folder.

Step3# Capture Identification Properties of the Test Object:

We can capture the identification properties using the Developers Tool of Chrome web browser. Analyzing the different properties such as, id, name, XPath, etc., we will pick the correct one which can be used in the scripting to perform any operations. In this “Puppeteer Automation Testing” tutorial, we will use the XPath in the script. Below steps to follow to get the XPATH or any other properties,

1. Open Developer Tools which available under “Menu -> More tools”, and go to Elements tab.

2. Using the Finder tool (clicking on arrow icon available in the left top corner of the Elements tab), highlight the test object from the application. Here, we will inspect the search box.

Puppeteer Automation Testing - Open Chrome Developer tool
Puppeteer Automation Testing – Open Chrome Developer tool

3. Analyze the highlighted source code to identify desire properties. To get the XPATH property of the test object, right-click on the highlighted section and click on “Copy-> Copy Xpath” to copy the XPATH property in the clipboard.

Puppeteer Automation Testing - Copy XPath
Puppeteer Automation Testing – Copy XPath

4. Now, paste the Xpath in the finder textbox and press enter to check if the Xpath is identifying the object uniquely.

Puppeteer Automation Testing - Check XPath
Puppeteer Automation Testing – Check XPath

5. Similarly, we need to capture the identification properties for another test object as well.

Step4# Puppeteer Automation Development Steps:

In order to complete the test case, we need to perform certain operations on web pages. For each of the operation, there are different methods available. The methods which are used in our scenario for “Puppeteer Automation Testing” are explained here.

Launch Application – After including the puppeteer, we need to launch the browser using the puppeteer—launch method. An object reference can be passed to this method to define for headless or headful browser. Then we need to create the instance of the web browser which is required to navigate the URL. Here, the async function is used to use the await keyword to handle the web synchronizer.

//Include the puppeteer package
const puppeteer = require('puppeteer'); 
 (async () => {
    //launching the headless browser
    const browser = await puppeteer.launch({ headless: true });
   //Create instance of the browser
    const page = await browser.newPage();
   //Navigate to the url
    await page.goto('https://www.amazon.in/');

The entire testing will be done in a headless browser. If we want to open the headful browser, we need to pass the object to the launch method as “{headless: false}”.

Check the existence – We need to use the method page.waitForXpath which will check the existence of the Xpath and return the reference of the test object. By testing the return reference, we can add a verification point in the test case.

	let searchBox = await page.waitForXPath("//*[@id='twotabsearchtextbox']",{ visible: true });
	if (searchBox === null) //Verification of the test object
		console.log('Amazon screen is not displayed');

Enter Data – Using the type method of that object reference, we can enter the text.

await searchBox.type("Testing Book");

Click on Element  – Similarly, using the click method of any object reference, we can perform click operations.

let btnSearch = await page.waitForXPath("//*/input[@id='nav-search-submit-button']",{visible:true });

Print message in the console  – Using the method console.log, we can print any message in the console as output.

console.log(‘Console lag has been generated’);

Refer to the new tab – Using the methods page.target and browser.waitforTarget, we can check and store the reference about new tab into a variable.

	const pageTarget = page.target();
	const newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
	//get the new page object:
	const page2 = await newTarget.page();

Capture Screenshot – Using the method page. Screenshot, a snapshot of the particular page has been taken and save as per the file name provided as an argument.

await page.screenshot({ path: ‘screenshot1.png’ });

Close Page and Browser – Using the method close, we can close both the web page and the browser.

	await page.close();
	await browser.close();

Wait Time – In certain cases, there is a requirement to wait for page loading or finishing of any dependant task; we need to pause the execution for a pre-defined time. To perform this, we can use the page.waitForTimeout method which can pause the execution based on the value (in mili-seconds) passed through the argument.

await page.waitForTimeout(2000);

Now we have learned about the basic technical steps to automate our functional scenario. Based on the knowledge, we can go through the Puppeteer Automation test case below. The detailed overview of the most frequently used classes and methods will be explained in subsequent posts.

 * @name Amazon search
const puppeteer = require('puppeteer');
const reportPath = 'C:\\LambdaGeeks\\puppteer_proj_sample\\output\\';
const screenshot = 'screen1.png';
// Used to export the file into a .docx file
try {
  (async () => {
    const browser = await puppeteer.launch({ headless: false });
    const pageNew = await browser.newPage()
    await pageNew.setViewport({ width: 1280, height: 800 });
    await pageNew.goto('https://www.amazon.in/');
	//Enter Search criteria
	let searchBox = await page.waitForXPath("//*[@id='twotabsearchtextbox']",{ visible: true });
	if (searchBox === null)
		console.log('Amazon screen is not displayed');
		await searchBox.type("Testing Book");
		console.log('Search criteria has been entered');
	//Clicked on search button
	let btnSearch = await pageNew.waitForXPath("//*/input[@id='nav-search-submit-button']",{ visible: true });
	if (btnSearch === null)
		console.log('Search button is not showing');
		await btnSearch.click();
		console.log('Clicked on search button');
	//Click on specific search result
	let myBook = await pageNew.waitForXPath("//*[contains(text(),'Selenium Testing Tools Cookbook Second Edition')]",{ visible: true })
	if (myBook === null)
		console.log('Book is not available');
		await myBook.click();
		console.log('Click on specific book to order');
	// Identify if the new tab has opened
	const pageTarget = pageNew.target();
	const newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
	//get the new page object:
	const page2 = await newTarget.pageNew();	
	await page2.setViewport({ width: 1280, height: 800 });
	//Add to cart
	let addToCart = await page2.waitForXPath("//*/input[@id='add-to-cart-button']",{ visible: true });
	if (addToCart === null)
		console.log('Add to cart button is not available');
		console.log('Click on add to Cart button');
		await addToCart.click();		
	//Verify add to cart process	
	let successMessage = await page2.waitForXPath("//*[contains(text(),'Added to Cart')]",{ visible: true });
	if (successMessage === null)
		console.log('Item is not added to cart');
		console.log('Item is added to cart successfully');		
	// Capture no of cart
	let cartCount = await page2.waitForXPath("//*/span[@id='nav-cart-count']",{ visible: true});
	let value = await page2.evaluate(el => el.textContent, cartCount)
	console.log('Cart count: ' + value);
	await page2.screenshot({ path: screenshot });
	await pageNew.waitForTimeout(2000);    
	await page2.close();
	await pageNew.close();
    await browser.close();
} catch (err) {

Step5# Puppeteer Automation Test Execution:

We can initiate the execution using the command node sample_script.js through the command prompt. During the execution, Chromium browser will be opened and automatically performed the functional steps and store the screenshot of the final page. The screenshot and the console output will look like below.

Puppeteer Automation Testing - Console Output
Puppeteer Automation Testing – Console Output
Puppeteer Automation Testing - Captured Screen
Puppeteer Automation Testing – Captured Screen


Throughout this Puppeteer Automation Testing Tutorial, we have learned about the detailed steps on Puppeteer Automation Testing. In the next Puppeteer tutorial, we will learn about the detailed overview of the most frequently used puppeteer classes and methods. Please click here to visit the reference portal for this Puppeteer Tutorial. 

About K Mondal

Hi, I am K. Mondal, I am associated with a leading organization. I am having 12+ years of working experience across domains e.g., application development, automation testing, IT Consultant. I am very much interested in learning different technologies. I am here to fulfill my aspiration and currently contributing as an Author and Website Developer both in LambdaGeeks.
Connect to LinkedIn- https://www.linkedin.com/in/kumaresh-mondal/

Leave a Comment

Your email address will not be published. Required fields are marked *