26. Test Lifecycle Hooks & Clean Isolation

The Test Lifecycle

import { test, expect } from "@playwright/test";

test.describe("User Profile Suite", () => {
test.beforeAll(async () => {
// Runs once before ALL tests in this describe block (e.g. seed test DB)
console.log("Suite initialization");
});

test.beforeEach(async ({ page }) => {
// Runs before EACH test. Excellent for common navigation.
await page.goto("/profile");
});

test.afterEach(async ({ page }) => {
// Runs after EACH test. Good for reporting or cleanup.
});

test.afterAll(async () => {
// Runs once after ALL tests finish.
console.log("Suite teardown");
});

test("can edit display name", async ({ page }) => {
await page.getByLabel("Name").fill("Dhanu");
await page.getByRole("button", { name: "Save" }).click();
});
});

---

Fixtures vs Hooks

| Criterion | Hooks (beforeEach) | Fixtures | | :--- | :--- | :--- | | Execution | Always runs for every test in file | Runs ONLY if requested by test params | | Data Sharing | Requires outer-scope let variables | Clean return via use(data) | | Reusability | File-bound (hard to share across files) | Globally shareable across entire repo |

Task

  • Implement recordLifecycleStep:
  • 1. Accept log array of strings.
  • 2. Accept step union: "beforeAll" | "beforeEach" | "test" | "afterEach" | "afterAll".
  • 3. Push step into log array.
πŸ’‘Common doubts
Did you like the problem?
Lesson 26 of 36
TypeScript
Loading code editor…
Next