Playwright Hooks

Hooks are special functions in Playwright that run before or after tests. They are mainly used to handle common setup and cleanup tasks that should not be repeated inside every test. Using hooks helps keep test code clean, reusable, and easier to maintain.

Playwright Hook Types

Playwright provides the following hooks:

     1. beforeAll: Runs once before all tests in a test file
     2. beforeEach: Runs before every test
     3. afterEach: Runs after every test
     4. afterAll: Runs once after all tests in a test file

Hooks are useful when you want to share setup logic, such as opening a URL or preparing test data, without rewriting it in every test.

Example: Using Playwright Hooks

Create a test file named hooksTest.spec.js.

import { test, expect } from '@playwright/test';
// Runs ONCE before all tests in this file
test.beforeAll(async () => {
    console.log('beforeAll: Runs once before all tests');
});
// Runs BEFORE each test
test.beforeEach(async ({ page }) => {
    console.log('beforeEach: Runs before every test');
    await page.goto('https://qafeast.com');
});
// Test 1
test('verify page title', async ({ page }) => {
    await page.click('#gdpr-cookie-accept');
    await expect(page).toHaveTitle(/QA Feast/i);
});
// Test 2
test('verify Tools menu is visible', async ({ page }) => {
    await page.click('#gdpr-cookie-accept');
    await expect(page.getByText('Tools', { exact: true })).toBeVisible();
});
// Runs AFTER each test
test.afterEach(async () => {
    console.log('afterEach: Runs after every test');
});
// Runs ONCE after all tests in this file
test.afterAll(async () => {
    console.log('afterAll: Runs once after all tests');
});

 

How This Works

     1. beforeAll runs one time before any test starts
     2. beforeEach opens the application before every test
     3. Each test executes independently
     4. afterEach runs after every test
     5. afterAll runs once after all tests complete

This hook setup ensures tests are isolated, common setup logic is reused, and cleanup is handled automatically

Running the Test

Use the following command to execute the test:

npx playwright test hooksTest.spec.js --project=chromium --headed --workers=1


Sample Output:

beforeAll: Runs once before all tests
beforeEach: Runs before every test
afterEach: Runs after every test
beforeEach: Runs before every test
afterEach: Runs after every test
afterAll: Runs once after all tests


Note: this output is showing the suite execution order
 

Related Tutorials