Playwright + JS · Lesson 26 of 35

0/35 done

Module 26: Hooks & Test Isolation

26. Test Lifecycle Hooks & Clean Isolation

16 minlesson

Try it yourself

Implement recordLifecycleStep:

  1. Accept log array and step string: "beforeAll" | "beforeEach" | "test" | "afterEach" | "afterAll".
  2. Push step into log array.

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

Lifecycle Hooks in Playwright

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

test.describe("User Profile Suite", () => {
  test.beforeEach(async ({ page }) => {
    await page.goto("/profile");
  });

  test.afterEach(async ({ page }) => {
    // Optional per-test cleanup
  });

  test("can update username", async ({ page }) => {
    await page.getByLabel("Username").fill("new_name");
    await page.getByRole("button", { name: "Save" }).click();
  });
});

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 + JS course (Playwright with JavaScript). 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 will cause failures.

Finished reading?

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

JavaScript
Skip