πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 27 of 100
Framework
Beginner

What are Playwright Hooks?

The Answer

Playwright Test provides four lifecycle hooks: `test.beforeAll`, `test.afterAll`, `test.beforeEach`, and `test.afterEach`. They allow you to run setup and teardown code at specific points in the test lifecycle.

Deep Dive Explanation

beforeAll/afterAll share a single worker context, so state CAN leak between tests when using them. Prefer beforeEach/afterEach (or Fixtures) for true test isolation.

example.spec.ts
import { test, expect } from '@playwright/test';

test.beforeAll(async ({ browser }) => {
  // Runs once before all tests in this file
  console.log('Suite started');
});

test.beforeEach(async ({ page }) => {
  // Runs before EACH test
  await page.goto('/');
});

test.afterEach(async ({ page }, testInfo) => {
  // Runs after EACH test
  if (testInfo.status !== testInfo.expectedStatus) {
    await page.screenshot({ path: `failure-${testInfo.title}.png` });
  }
});

test.afterAll(async () => {
  // Runs once after all tests
  console.log('Suite finished');
});