What are the hooks in puppeteer and how to use hooks in puppeteer? In this puppeteer tutorial, We will see how to implement hooks in puppeteer. Let’s see what are the available hooks in puppeteer.
Hooks in puppeteer
hooks in puppeteer are used to manage the automation workflow. hooks help to add any action during the execution or at any stage of the automation suite. Let’s say I want to perform an action before each test case or after test case. We can solve this problem using hooks.
Types of hooks in puppeteer
Mainly there 4 types of hooks available in puppeteer.
before
Before is used to perform any action before the suite execution. Like, launch the browser.
before(async function(){ console.log("Before..............."); })
after
After is used to perform any action after the suite execution. Like, close the browser.
after(async function(){ console.log("After .......") });
beforeEach
BeforeEach is used to perform any action before every test case. It will execute before every “It” block.
beforeEach(async function(){ console.log("Before Each: "); })
afterEach
AfterEach is used to perform any action after every test case. It will execute after every “It” block.
afterEach(async function(){ console.log("After Each: "); })
Implements of hooks in puppeteer
Let’s see how to implement hooks in puppeteer.
const puppeteer = require('puppeteer') describe("Wait in puppeteer",()=>{ before(async function(){ console.log("Before..............."); }) beforeEach(async function(){ console.log("Before Each: "); }) afterEach(async function(){ console.log("After Each: "); }) after(async function(){ console.log("After .......") }); });
Puppeteer example to implement Hooks
In this puppeteer example. We are going to implement 2 test cases.
- Verify the page title
- Verify the first heading of the page.
const puppeteer = require('puppeteer') const expect = require('chai').expect describe("Hooks in puppeteer",()=>{ let browser let page before(async function(){ browser = await puppeteer.launch({ headless:false, slowMo:100 }) page = await browser.newPage() await page.goto("https://devexpress.github.io/testcafe/example/") }) beforeEach(async function(){ console.log("Before Each..................... ") }) afterEach(async function(){ console.log("After Each.............. ") }) it("Verify page tittle",async()=>{ const ptitle = await page.title() expect(ptitle).include('Example') }) it("Verify Heading", async()=>{ const heading = await page.$eval('H1', ele => ele.textContent) expect(heading).to.be.a('string','Example') }) after(async function(){ await browser.close() }) });