How to use assertion in puppeteer and chai

How to use assertion in puppeteer. In this puppeteer tutorial, We will how to use assertion in puppeteer and Chai.

Assertion in puppeteer

To use assertion in puppeteer, We need another NodeJS library called chai. that contains expect() function that is used to perform assertion in puppeteer. Let’s see some example

include expect() in the script

const expect = require('chai').expect

during the automation, we need many combinations of data to verify or perform the assertion. In the below examples, I am going to cover some of them with the example

Assertion on a string using puppeteer

Assertion to verify the exact match of a string in puppeteer.
expect(Message).to.be.a('string','Example');

Assertion on an integer using puppeteer

Assertion to verify the exact match of an integer value in puppeteer.

expect(count).to.equal(9);

Include Assertion on a string using puppeteer

Assertion to verify some part of a string in puppeteer. for example, I need to verify the word “puppeteer” word from the string “This is puppeteer automation tutorial”.  So let’s verify the string contains the word or not.

expect(Message).to.include('puppeteer');

Puppeteer example of using assertion

In this puppeteer example, Test Scenario is:

Launch the browser and navigate to the URL.

Get the page heading text.

and count the number of the paragraph on the page.

And verify heading is equals to “Example”

And verify the heading contains text as “Exa”

And verify the paragraph count is equals to 9.

const puppeteer = require('puppeteer')
const expect = require('chai').expect

describe("Get Element Text and Element Count",()=>{
     it("Handle Input and buuton 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 page.$eval('H1', ele => ele.textContent);
    console.log("Heading text: "+Message);

    const count =  await page.$$eval('p', ele => ele.length);
    console.log("Count p tag in the page: "+count);
    
    expect(Message).to.be.a('string','Example');
    expect(count).to.equal(9);
    expect(Message).to.include('Exa');

    await page.waitFor(5000);
    await page.close();

  });

    });