Playwright Test Hooks

Profile picture for user arilio666

The playwright provides a test function to declare tests and contains expected tasks that help us write assertions. Today in this article, we will be looking at different test hooks used by playwright.

afterAll Hook

  • afterAll hooks, once declared, execute tests after all tests.
  • Running in the scope of the test file runs after all tests in the file.
  • When used inside the test describe, it runs after all tests in the group.
  • If multiple afterAll is used, they will run in the order of their registration.
test.afterAll('do this after all test ends', async ({ page }) => {
    console.log('After all test')
  });
  • Hook runs again with the new worker as the worker process is restarted on test failure.

afterEach Hook

  • This Hook is executed after each test, and when called in, a scope of test file runs after each test in the file.
  • When used inside the test describe, it runs after each test in the group.
  • If multiple afterEach is used, they will run in the order of their registration.
test.afterEach('do this after each test ends', async ({ page }) => {
    console.log('Run After Each Test Step')
});
  • We can access all the fixtures as the test function itself.

beforeAll Hook

  • This Hook is executed before all tests and, when called in the scope of the test file, runs before all the tests in the file.
  • When used inside the test describe, it runs before all tests in the group.
  • If multiple beforeAll is used, they will run in the order of their registration.
  • beforeAll hook runs again with a new worker as the worker process is restarted on test failure.
test.beforeAll('runbefore', async ()=>{
console.log('Ran before')
});

beforeEach Hook

  • This Hook is executed before each test and, when called in the scope of the test file, runs before each test in the file.
  • When used inside the test, describe it runs before each test in the group.
  • If multiple beforeEach is used, they will run in the order of their registration.
  • We can access all the fixtures as the test function itself.
const { test, expect } = require('@playwright/test');

test.beforeEach(async ({ page }, testInfo) => {
  await page.goto('https://www.programsbuzz.com/');
});

test('my test', async ({ page }) => {
  expect(page.url()).toBe('https://www.programsbuzz.com/');
});