Commands that come with puppeteer are very plain but they do their designated job. But as a user, we always expect little more from the tools.
Custom commands can reduce the number of lines used in our test code. We can add more functionalities to the already existing functions in the tool. Customize existing commands will make our task easy.
Customizing a command means, we are actually adding more functionalities to the same command. And there will be no difference will be there for calling the same Command. Only CypressIO support these customization commands but not puppeteer
// Before customization
await page.click("locator")
// After customization
await page.click("locator") // there is no difference in calling
Wrapping a command means we will be creating a new function and in this function, we will be using existing commands along with other commands that we need for our customization. In simple words, create a library method.
// Before wrapping
await page.click("locator")
// After wrapping
await ClickMe(page, "locator") // total difference in calling
Some common functions that we need more often during automation are:
Percy with Puppeteer Integration
By default, the puppeteer waits for some time(30 seconds) if a particular element is not present, and this is applicable for all the operations.
When we wrap the click() function here, we are going to add more time to wait for this element alone. Along with the wait, we are going to wrap the click() function inside try and catch
The below code should go in a separate file. Here,
module.exports = {
ClickMe: async function(page, selector){
try{
await page.waitForSelector(selector);
await page.click(selector);
console.log(await "Clicked on : "+selector)
}catch(error){
throw new Error('Could not click on the')
}
}
}
Our test file:
const puppeteer = require('puppeteer');
const {ClickMe} = require("./custom-commands")
async function run(){
const browser = await puppeteer.launch({headless:false})
const page = await browser.newPage()
await page.goto('https://google.com/')
await ClickMe(page, "div>a")
}
run()

Similar to the click command, you can wrap all other commands in puppeteer.
I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.