Playwright BeforeEach and AfterEach Hooks

Profile picture for user arilio666

This article will discuss the beforeEach and afterEach hook in playwright.

Provided by jest and mocha, the before and after each hook is used to run setup and teardown code before and after each test case.

For example, let's say you have a test suite for a web application, and you need to log in to the application before each test case is executed. You could use the "beforeEach" hook to execute the login code before each test case like this:

test.beforeEach(async ({ page }, testInfo) => {
   console.log(`Running ${testInfo.title}`);
   await page.goto('https://the-internet.herokuapp.com/nested_frames');
 });

Similarly, you may need to clean up any data or resources created during the test after executing each test case. In this case, you could use the "afterEach" hook to execute the cleanup code like this:

test.afterEach(async ({ page }, testInfo) => {
    console.log(`Finished ${testInfo.title} with status ${testInfo.status}`);
  
    if (testInfo.status !== testInfo.expectedStatus)
      console.log(`Failed to run and ended up at ${page.url()}`);
  });

This way, we can log the status and teardown tests after each completion.

const {test, expect} = require('@playwright/test');

test.afterEach(async ({ page }, testInfo) => {
    console.log(`Finished ${testInfo.title} with status ${testInfo.status}`);
  
    if (testInfo.status !== testInfo.expectedStatus)
      console.log(`Failed to run and ended up at ${page.url()}`);
  });
 
 test.beforeEach(async ({ page }, testInfo) => {
   console.log(`Running ${testInfo.title}`);
   await page.goto('https://the-internet.herokuapp.com/nested_frames');
 });

test('FrameHandle', async ({page})=> 
{
const parentFrame = await page.frameLocator("//frame[@name='frame-top']");
const middleFrame = await parentFrame.frameLocator('frame[name="frame-middle"]').locator('body');
const text = await middleFrame.textContent();
console.log(text)
const rightFrame = await parentFrame.frameLocator("frame[name='frame-right']").locator('body')

const rtext = await rightFrame.textContent();
console.log(rtext)
const leftFrame = await parentFrame.frameLocator('frame[name="frame-left"]').locator('body')

const ltext = await leftFrame.textContent()
console.log(ltext)
});
  • Here we have run simple frames handle tests where in the beforeEach, we navigated to the site and logged a custom response with the title.
  • In the afterEach, we logged the title info and status of the test, and if it was unsuccessful, we also gave an if condition.
  • This is how we can implement these hooks effectively in playwright.