Playwright + TS · Lesson 26 of 36

0/36 done

Module 26: Hooks & Test Isolation

26. Test Lifecycle Hooks & Clean Isolation

16 minlesson

Try it yourself

Implement recordLifecycleStep:

  1. Accept log array of strings.
  2. Accept step union: "beforeAll" | "beforeEach" | "test" | "afterEach" | "afterAll".
  3. Push step into log array.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

The Test Lifecycle

typescript
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 |

Key Takeaways & Walkthrough Summary

Lifecycle hooks control how tests execute before and after each suite. In this lesson, we will explore beforeAll, beforeEach, afterEach, and afterAll, and discuss why strict test isolation is essential for running reliable tests in parallel. Let's master test lifecycles!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why should tests never depend on each other's execution order?

Playwright executes tests in parallel across multiple worker processes. If Test B relies on data created by Test A, running in parallel or running Test B alone will immediately fail.

Does afterEach run if the test throws an assertion failure?

Yes! afterEach and fixture teardown are guaranteed to run even if an assertion or unhandled error crashes the test.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip