Playwright + TS · Lesson 26 of 36
Module 26: Hooks & Test Isolation
Try it yourself
Implement recordLifecycleStep:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
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();
});
});| 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 |
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.
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.
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.