| | |

Playwright 12 ๐ŸŽญ Hooks โ€” beforeEach, afterEach, and Shared Setup

โฑ๏ธ Estimated read: 10 min | |

Playwright’s test runner has its own hooks, and they are a separate mechanism from fixtures. The hooks are test.beforeAll, test.beforeEach, test.afterEach, and test.afterAll. They scope to the file or the describe block that contains them, they run in the same nesting order as the other test runners, and they have their own page fixture instance per test. The relationship to the previous chapter’s fixtures is the part that matters: a fixture is lazy and composable, a hook is unconditional and runs for every test in its scope, and the two are not interchangeable.

This chapter covers the four hooks and their order, the difference between a hook and a fixture, and the shared setup patterns that use one or the other. The sections that follow walk through the hook scoping, the test.describe blocks that contain the hooks, and the cases where a fixture is the better tool.

Key point: test.beforeAll/beforeEach/afterEach/afterAll are unconditional and scoped to the file or the describe block, while a fixture is lazy and runs only for the test that requests it; use the hook for the setup every test needs and the fixture for the setup one test needs.


a. The four hooks and their order

test.beforeAll runs once before the first test in the file or the describe block. test.beforeEach runs before every test in the scope. test.afterEach runs after every test. test.afterAll runs once after the last test. Setup runs outermost-first and teardown runs innermost-first.

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

test.describe("dashboard", () => {
  test.beforeAll(async () => {
    console.log("once before the block");
  });

  test.beforeEach(async ({ page }) => {
    await page.goto("/dashboard");
  });

  test.afterEach(async ({ page }) => {
    await page.goto("/logout");
  });

  test.afterAll(async () => {
    console.log("once after the block");
  });

  test("shows the heading", async ({ page }) => {
    await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
  });
});

The beforeEach receives the page fixture, and the fixture is a fresh page for each test. The hook’s page is the same page the test receives, because Playwright injects the same instance into the hook and the test body. The beforeEach is where the navigation belongs: every test in the block starts from the page the hook visited, and the test body contains only the actions and assertions specific to that test.

The test.describe block is the scoping container. A beforeEach outside a describe runs for every test in the file; a beforeEach inside a describe runs only for the tests in that block. The nested describe blocks nest the hooks, and the order is outermost-first for setup and innermost-first for teardown.


b. The hook versus the fixture

The hook and the fixture both provide setup, and the difference is when the setup runs. A beforeEach runs before every test in its scope, whether or not the test uses what the hook sets up. A fixture runs only when the test requests it in its parameter list.

// Hook: runs before every test in the block
test.beforeEach(async ({ page }) => {
  await page.goto("/dashboard");
});

// Fixture: runs only for the test that requests it
test("seeds the admin", async ({ adminPage }) => {
  // adminPage is created only for this test
});

The unconditional hook is the right tool when every test in the block needs the same setupโ€”a page.goto to the base URL, a seed that resets the database, a login that every test requires. The lazy fixture is the right tool when only some tests need the setup, or when the setup composes with other setup. A beforeEach that logs in for every test is a beforeEach that wastes the login on the tests that do not need it; a fixture that logs in is requested only by the tests that do.

The fixture also has the teardown guarantee. A beforeEach that creates a resource has no built-in teardown; the resource is released in an afterEach that must be written separately. A fixture’s teardown is the code after use, and it runs even when the test fails. The fixture is the safer tool for a resource that must be released.

The test.use call is the mechanism for a per-file or per-describe configuration override. It sets an option fixture’s value for the block, which is how a suite runs the same tests under a different role or a different base URL.

test.describe("admin", () => {
  test.use({ storageState: "admin.json" });

  test("shows the admin menu", async ({ page }) => {
    await page.goto("/admin");
    await expect(page.getByRole("navigation")).toBeVisible();
  });
});

c. The shared setup and the parallel concern

The beforeAll is the hook for the setup that runs once for the blockโ€”a database seed, a server start, a file write. The afterAll is the teardown that runs once. The two are the pair for a resource that the whole block shares.

test.describe("with seeded data", () => {
  test.beforeAll(async ({ request }) => {
    await request.post("/api/seed");
  });

  test.afterAll(async ({ request }) => {
    await request.delete("/api/seed");
  });

  test("finds the seeded user", async ({ page }) => {
    await page.goto("/users");
    await expect(page.getByText("Seeded User")).toBeVisible();
  });
});

The beforeAll and afterAll hooks do not receive the page fixture in the same way as the beforeEach. Playwright’s beforeAll runs in a worker context, and the page fixture is not available unless it is created explicitly. A beforeAll that needs a page creates one from the browser fixture.

The parallel concern is the reason the beforeAll is the exception rather than the rule. Playwright runs test files in parallel by default, and the tests within a file run in the same worker sequentially. A beforeAll that seeds the database affects every test in the file, and a test that mutates the seed breaks the next test. The beforeEach reset is the safe pattern; the beforeAll is for the data that no test mutates.

The test.describe.serial and test.describe.parallel modes change the execution model for a block. The serial mode runs the tests in the block in order and stops the block at the first failure; the parallel mode runs the tests in the block in parallel, which requires each test to be independent.

test.describe.serial("checkout flow", () => {
  test("adds to cart", async ({ page }) => { ... });
  test("checks out", async ({ page }) => { ... }); // depends on the first
});

Complete Example Session

// ============================================
// PART 1: THE beforeEach AND afterEach
// ============================================
import { test, expect } from "@playwright/test";

test.describe("dashboard", () => {
  test.beforeEach(async ({ page }) => {
    await page.goto("/dashboard");
  });

  test.afterEach(async ({ page }) => {
    await page.goto("/logout");
  });

  test("shows the heading", async ({ page }) => {
    await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
  });

  test("shows the sidebar", async ({ page }) => {
    await expect(page.getByRole("navigation")).toBeVisible();
  });
});

// ============================================
// PART 2: THE beforeAll AND afterAll
// ============================================
test.describe("seeded", () => {
  test.beforeAll(async ({ request }) => {
    await request.post("/api/seed");
  });

  test.afterAll(async ({ request }) => {
    await request.delete("/api/seed");
  });

  test("finds the seeded user", async ({ page }) => {
    await page.goto("/users");
    await expect(page.getByText("Seeded User")).toBeVisible();
  });
});

// ============================================
// PART 3: THE test.use OVERRIDE
// ============================================
test.describe("admin", () => {
  test.use({ storageState: "admin.json" });

  test("shows the admin menu", async ({ page }) => {
    await page.goto("/admin");
    await expect(page.getByRole("navigation")).toBeVisible();
  });
});

// ============================================
// PART 4: THE SERIAL BLOCK
// ============================================
test.describe.serial("checkout", () => {
  test("adds to cart", async ({ page }) => {
    await page.goto("/products");
    await page.getByRole("button", { name: "Add" }).click();
  });

  test("checks out", async ({ page }) => {
    await page.goto("/cart");
    await expect(page.getByText("1 item")).toBeVisible();
  });
});

The parts covered the beforeEach/afterEach pair, the beforeAll/afterAll seed, the test.use override, and the serial block.


Quick Reference

Hooks

HookRunsScope
test.beforeAllOnce per blockFile or describe
test.beforeEachBefore every testFile or describe
test.afterEachAfter every testFile or describe
test.afterAllOnce per blockFile or describe

Hook vs Fixture

AspectHookFixture
RunsUnconditionallyWhen requested
TeardownManual afterEachCode after use
CompositionNoneDepends on fixtures
UseShared setupPer-test setup

Override and Modes

CallEffect
test.use({ ... })Override options for the block
test.describe.serialRun tests in order
test.describe.parallelRun tests in parallel
test.describe.configureSet mode or retries

Best Practices

โœ… Do This:

// Use beforeEach for shared navigation
test.beforeEach(async ({ page }) => { await page.goto("/"); }); // โœ…

// Use test.use for a role override
test.use({ storageState: "admin.json" });                       // โœ…

// Use serial for a dependent flow
test.describe.serial("checkout", () => { ... });                // โœ…

โŒ Don’t Do This:

// Use beforeEach for a setup only one test needs
test.beforeEach(async ({ page }) => { await login(page); });   // โŒ

// Seed in beforeAll and mutate the seed
test.beforeAll(async () => { await seed(); });                  // โŒ (unless no test mutates)

// Forget the afterEach for a resource
test.beforeEach(async ({ page }) => { await openModal(page); }); // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Slow suiteLogin in beforeEach for every testUse a fixture
State leaks between testsbeforeAll seed mutatedReset in beforeEach
Page unavailable in beforeAllThe fixture is per-testCreate it from browser
Flaky parallel testsShared stateUse serial or isolate

Real-World Examples

1. beforeEach navigation

test.beforeEach(async ({ page }) => { await page.goto("/dashboard"); });

2. afterEach cleanup

test.afterEach(async ({ page }) => { await page.goto("/logout"); });

3. beforeAll seed

test.beforeAll(async ({ request }) => { await request.post("/api/seed"); });

4. afterAll teardown

test.afterAll(async ({ request }) => { await request.delete("/api/seed"); });

5. test.use override

test.use({ storageState: "admin.json" });

6. Serial block

test.describe.serial("checkout", () => { ... });

7. Configure retries

test.describe.configure({ retries: 2 });

8. Nested describe

test.describe("outer", () => { test.describe("inner", () => { ... }); });

9. Hook with page

test.beforeEach(async ({ page }) => { ... });

10. Hook in beforeAll with browser

test.beforeAll(async ({ browser }) => { const page = await browser.newPage(); });

Visual

Hook Order

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  test.beforeAll          (1)                            โ”‚
โ”‚  test.beforeEach         (2)                            โ”‚
โ”‚    test body             (3)                            โ”‚
โ”‚  test.afterEach          (4)                            โ”‚
โ”‚  test.afterAll           (5)                            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Hook vs Fixture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  HOOK                          FIXTURE                  โ”‚
โ”‚                                                         โ”‚
โ”‚  Runs for every test           Runs when requested      โ”‚
โ”‚  No built-in teardown          Teardown after use       โ”‚
โ”‚  before/after each             Lazy, composable         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Scope

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  test.beforeEach (file scope)                           โ”‚
โ”‚    test.describe("block")                               โ”‚
โ”‚      test.beforeEach (block scope)                      โ”‚
โ”‚        test (both hooks run)                            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Serial Mode

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  test.describe.serial("checkout", () => {               โ”‚
โ”‚    test("adds to cart", ...)                            โ”‚
โ”‚    test("checks out", ...)                              โ”‚
โ”‚  });                                                    โ”‚
โ”‚                                                         โ”‚
โ”‚  Runs in order; stops the block at the first failure.   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Per-suite setuptest.beforeAll
Per-test setuptest.beforeEach
Per-test teardowntest.afterEach
Per-suite teardowntest.afterAll
Override optionstest.use({ ... })
Serial blocktest.describe.serial
Parallel blocktest.describe.parallel

Key takeaways:

  • The hooks are unconditional. test.beforeEach runs for every test in the block, whether or not the test uses what the hook sets up. The fixture is the lazy alternative that runs only for the test that requests it.
  • The hook has no built-in teardown. A resource created in beforeEach is released in a separate afterEach, and the developer must remember to write it. A fixture’s teardown is the code after use, and it runs even when the test fails.
  • test.use overrides options per block. The storageState, baseURL, and other options are set for the describe block, which is how a suite runs the same tests under a different role or a different environment.
  • test.describe.serial is for dependent tests. The mode runs the tests in order and stops the block at the first failure, which is the pattern for a checkout flow where each step depends on the previous one.
  • The beforeAll is the exception, not the rule. The hook runs once for the file, and a test that mutates the shared state breaks the next test. The beforeEach reset is the safe pattern; the beforeAll is for the data no test mutates.

Remember: The hooks are the unconditional setup, and the fixtures are the lazy setup. The beforeEach is for the navigation and the reset every test needs; the fixture is for the setup that only some tests need, or the resource that must be released. The test.use overrides the options for a block, and the serial mode handles the dependent flow. Put the shared navigation in the hook, the composable setup in the fixture, and the mutation-prone state in the beforeEach reset.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!