Custom Commands in puppeteer

Customize existing commands will make our task easy. In this puppeteer tutorial, Let’s how to customize commands in puppeteer.

Some common functions that we need more often during the automation are Click(), getText(), getCount(), typeText() etc. So how can we change this function and modify them according to our requirements?.

Customize Click() in puppeteer

Every time when we need to click on any HTML element we need to perform two major steps.

  1. Wait for the element.
  2. Click to element.
click: async function(page, selector){
    try{
        await page.waitForSelector(selector);
        await page.click(selector);
    }catch(error){
        throw new Error('Could not click on the')
        
    }
}

Now after customization just call Click(page, selector). It will take two parameters as input Page and selector.

Customize getText() in puppeteer

Every time when we need to get a text from any HTML element we need to perform two major steps.

  1. Wait for the element.
  2. Get the text from the element.
getText: async function(page, selector){
     try{
         await page.waitForSelector(selector);
         return await page.$eval(selector, element => element.textContent)
     }catch(error){
         throw new Error('Could not get text from selector' +{selector});
     }
 }

Now, it will take two parameters as an argument and return a text.

Customize getCount() in puppeteer

getCount: async function(page, selector){
        try{
            await page.waitForSelector(selector);
            return page.$$eval(selector, element => element.length);
        }catch(error){

            throw new Error('Could not found the element '+{selector});
        }
    }

Customize typeText() in puppeteer

typeText: async function(page, selector, text){
        try{
            await page.waitForSelector(selector);
        await page.type(selector,text);
        }catch(error){
            throw new Error('Could not found the element typeText');
        }
    }

Customize shouldNotExist() in puppeteer

It will check and return false if the element is available and true if the element is not available on the page.

shouldNotExist: async function(page,selector){
    try {
        await page.waitForSelector(selector, {hiddern:true})
    } catch (error) {
        throw new Error('Could not found the element shouldNotExist')
    }
}

Use Custom commands in puppeteer

Now let’s see how to use these custom commands in puppeteer script.

const Message = await getText(page,'H1');
console.log("Heading text: "+Message);

Example of custom commands in puppeteer.

Helper.js

This file contains all the custom commands

module.exports = {

    click: async function(page, selector){
        try{
            await page.waitForSelector(selector);
            await page.click(selector);
        }catch(error){
            throw new Error('Could not click on the')
            
        }
    },
    getText: async function(page, selector){
        try{
            await page.waitForSelector(selector);
            return await page.$eval(selector, element => element.textContent)
        }catch(error){
            throw new Error('Could not get text from selector' +{selector});
        }
    },
    getCount: async function(page, selector){
        try{
            await page.waitForSelector(selector);
            return page.$$eval(selector, element => element.length);
        }catch(error){

            throw new Error('Could not found the element '+{selector});
        }
    },
    typeText: async function(page, selector, text){
        try{
            await page.waitForSelector(selector);
        await page.type(selector,text);
        }catch(error){
            throw new Error('Could not found the element typeText');
        }
    },
    waitForText: async function(page, selector, text){
        try {
            await page.waitForSelector(selector);
            await page.waitForFunction(selector, text => {
                document.querySelector(selector).innerText.includes(text),
                {},
                selector,
                text;
                });
        } catch (error) {
            throw new Error('Could not found the element waitForText')
        }
       
    },
    shouldNotExist: async function(page,selector){
        try {
            await page.waitForSelector(selector, {hiddern:true})
        } catch (error) {
            throw new Error('Could not found the element shouldNotExist')
        }
    }
}

Example.test.js

This file contains the test step where we calling all the custom commands from helper.js

const puppeteer = require('puppeteer');
const expect = require('chai').expect;
const {click} = require('../lib/helper');
const {getText} = require('../lib/helper');
const {getCount} = require('../lib/helper')
const {typeText} = require('../lib/helper')
const {waitForText} = require('../lib/helper')
const {shouldNotExist} = require('../lib/helper')

describe("Get Element Text and Element Count",()=>{

     it("Handle Input and button in puppeteer",async()=>{
    const browser = await puppeteer.launch({
      headless:false,
      slowMo:100
    })
    const page = await browser.newPage()
    await page.goto("https://devexpress.github.io/testcafe/example/");
 
    // The text of H1 element..
   
    const Message = await getText(page,'H1');
    console.log("Heading text: "+Message);
    const count = await getCount(page,'p');
    console.log("Count p tag in the page: "+count);
    await typeText(page,"#developer-name", "Bhupendra Patidar");

    //Wait for text
    await page.waitFor(5000);
    await waitForText(page,'H1','Example');
    await shouldNotExist(page,'#testcafe-rank');
    await click(page,'#remote-testing');

    //Assertion...
    expect(Message).to.be.a('string','Example');
    expect(count).to.equal(9);
    expect(Message).to.include('Exa');

    //Wait and close browser
    await page.waitFor(5000);
    await browser.close();
  });
    });