#Hooks and describe blocks
AddedA test file is more than a list of test(...) calls. test.describe groups tests under a shared title, and hooks run code around them: beforeEach and afterEach around every test in the group, beforeAll and afterAll once around the whole group. Groups can nest, and an inner group's hooks run inside the outer group's.
The mental model is layers of an onion. The outermost layer is the file, then each describe, then the test itself. Before a test, Playwright walks inwards running every beforeEach it passes; after the test, it walks back outwards running the afterEach hooks in reverse. beforeAll and afterAll wrap the whole onion once, not each test.
One thing surprises almost everyone: beforeAll runs once per worker process, not once per file or per run. If a worker crashes or a test fails, Playwright throws that worker away and starts a new one, and beforeAll runs again in it. So beforeAll is the wrong place for "do this exactly once for the whole suite" (that's globalSetup or a setup project, Chapter 8), and it should never leave state that a later test depends on.
Here's every hook printing when it runs, so the order is visible:
import { test, expect } from "@playwright/test";
test.beforeAll(async () => {
console.log("beforeAll (file)");
});
test.afterAll(async () => {
console.log("afterAll (file)");
});
test.beforeEach(async ({ page }, testInfo) => {
console.log(` beforeEach (file): ${testInfo.title}`);
await page.goto("/practice/");
await page.getByLabel("Username").fill("rohit");
await page.getByLabel("Password").fill("playwright");
await page.getByRole("button", { name: "Sign in" }).click();
});
test.afterEach(async ({}, testInfo) => {
console.log(` afterEach (file): ${testInfo.title} → ${testInfo.status}`);
});
test("shows all eight products", async ({ page }) => {
console.log(" test body");
await expect(page.getByRole("listitem")).toHaveCount(8);
});
test.describe("search", () => {
test.beforeEach(async ({ page }) => {
console.log(" beforeEach (search)");
await expect(page.getByRole("listitem")).toHaveCount(8);
});
test("finds the mouse", async ({ page }) => {
console.log(" test body");
await page.getByLabel("Search products").fill("wireless");
await expect(page.getByRole("listitem")).toHaveText([/Wireless Mouse/]);
});
test("says when nothing matches", async ({ page }) => {
console.log(" test body");
await page.getByLabel("Search products").fill("banana");
await expect(page.getByText("No products match “banana”.")).toBeVisible();
});
});Running 3 tests using 1 worker
beforeAll (file)
beforeEach (file): shows all eight products
test body
afterEach (file): shows all eight products → passed
✓ 1 [chromium] › tests/hooks.spec.ts:21:1 › shows all eight products (1.5s)
beforeEach (file): finds the mouse
beforeEach (search)
test body
afterEach (file): finds the mouse → passed
✓ 2 [chromium] › tests/hooks.spec.ts:32:3 › search › finds the mouse (2.2s)
beforeEach (file): says when nothing matches
beforeEach (search)
test body
afterEach (file): says when nothing matches → passed
afterAll (file)
✓ 3 [chromium] › tests/hooks.spec.ts:38:3 › search › says when nothing matches (2.2s)
3 passed (6.4s)beforeAll (file)prints once, before the first test: one file, one worker, so onebeforeAll.afterAll (file)prints once at the very end, after the lastafterEach(the reporter happens to print the third test's ✓ line just after it; the console lines are in true order).- Every test gets the file's
beforeEachfirst. It uses thepagefixture and signs in, so each test starts signed in on the products page, in its own fresh context. Nothing is shared between the three tests except what the code itself shares. - The two tests inside
describe("search")also get the group's ownbeforeEach, which runs after the file's one (outside in). It waits for the eight products, so a search never starts before the list has loaded. afterEachsees the result:testInfo.statusispassedfor each. AnafterEachis the place for per-test reporting or attaching extra evidence on failure (if (testInfo.status !== testInfo.expectedStatus) …).- The
describetitle becomes part of each test's name (search › finds the mouse), which is how you'd filter them:npx playwright test -g "search". - If you changed the first test to fail, its worker would be replaced (per the docs, "worker process is restarted on test failures"), and
beforeAll (file)would print a second time before the next test. A quick three-test file whose first test fails, run while writing this page, printedbeforeAlltwice. That's whybeforeAllmust never be "run once per suite" logic.
The opposite switch, test.describe.configure({ mode: "parallel" }), lets the tests of one file run at the same time in different workers (the config's fullyParallel: true does the same for every file). It only works if every test is independent, which is one more reason to never write the serial pattern above by accident. Chapter 12 covers workers in depth.
A long journey test (sign in, add, check out) can fail anywhere, and "line 37" isn't a great report. test.step(title, body) groups actions under a name that appears in the HTML report, the trace viewer and, with printSteps, in the terminal. A step returns whatever its body returns. Options added later: box (1.39) points errors at the step call instead of the line inside it, timeout (1.50), and subtitle and params (1.63).
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
reporter: [["list", { printSteps: true }]],
use: { baseURL: "https://rohit-playwright.pages.dev" },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});import { test, expect } from "@playwright/test";
test("buy a keyboard", async ({ page }) => {
await test.step("sign in as rohit", async () => {
await page.goto("/practice/");
await page.getByLabel("Username").fill("rohit");
await page.getByLabel("Password").fill("playwright");
await page.getByRole("button", { name: "Sign in" }).click();
});
const total = await test.step("add the keyboard and open the cart", async () => {
await page.getByRole("listitem").filter({ hasText: "Compact Keyboard" }).getByRole("button", { name: "Add to cart" }).click();
await page.getByRole("link", { name: "Cart (1)" }).click();
return page.getByTestId("cart-total").textContent();
});
await test.step("check out", async () => {
await page.getByRole("link", { name: "Checkout" }).click();
await page.getByLabel("Email").fill("rohit@example.com");
await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");
await page.getByLabel("I agree to the terms").check();
await page.getByRole("button", { name: "Place order" }).click();
});
await expect(page.getByText(`Total paid on delivery: ${total}`)).toBeVisible();
});Running 1 test using 1 worker
1.1 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard › sign in as rohit (153ms)
1.2 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard › add the keyboard and open the cart (1.4s)
1.3 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard › check out (114ms)
✓ 1 [chromium] › tests/journey.spec.ts:3:1 › buy a keyboard (3.0s)
1 passed (3.4s)printSteps: truemakes the list reporter print a line for eachtest.stepas it finishes, numbered under its test (1.1,1.2,1.3) and with its own time, before the test's own ✓ line. Without it you'd see only the test line (the steps still appear in the HTML report and trace).- The second step returns a value: the cart total text ("$59.00").
test.stepresolves to whatever its body returns, so steps can hand data to later code without a module variable. - Steps are only labels around normal code: there's no extra waiting or retrying, and a failure inside a step fails the test as usual, with the step's name in the report so you can see where in the journey it broke. Notice "check out" takes only about a tenth of a second: clicking Place order returns at once, and the 1.2-second wait for the order happens in the final
expect, outside any step. A step times exactly the code inside it. - Use steps for long journeys and inside page-object methods and fixtures (a
signIn()method wrapped in a step reads as one line in the report). Don't use them to split what should be separate tests.