Playwright 12 ๐ญ Hooks โ beforeEach, afterEach, and Shared Setup
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
| Hook | Runs | Scope |
|---|---|---|
test.beforeAll | Once per block | File or describe |
test.beforeEach | Before every test | File or describe |
test.afterEach | After every test | File or describe |
test.afterAll | Once per block | File or describe |
Hook vs Fixture
| Aspect | Hook | Fixture |
|---|---|---|
| Runs | Unconditionally | When requested |
| Teardown | Manual afterEach | Code after use |
| Composition | None | Depends on fixtures |
| Use | Shared setup | Per-test setup |
Override and Modes
| Call | Effect |
|---|---|
test.use({ ... }) | Override options for the block |
test.describe.serial | Run tests in order |
test.describe.parallel | Run tests in parallel |
test.describe.configure | Set 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Slow suite | Login in beforeEach for every test | Use a fixture |
| State leaks between tests | beforeAll seed mutated | Reset in beforeEach |
Page unavailable in beforeAll | The fixture is per-test | Create it from browser |
| Flaky parallel tests | Shared state | Use 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
| Item | Value |
|---|---|
| Per-suite setup | test.beforeAll |
| Per-test setup | test.beforeEach |
| Per-test teardown | test.afterEach |
| Per-suite teardown | test.afterAll |
| Override options | test.use({ ... }) |
| Serial block | test.describe.serial |
| Parallel block | test.describe.parallel |
Key takeaways:
- The hooks are unconditional.
test.beforeEachruns 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
beforeEachis released in a separateafterEach, and the developer must remember to write it. A fixture’s teardown is the code afteruse, and it runs even when the test fails. test.useoverrides options per block. ThestorageState,baseURL, and other options are set for thedescribeblock, which is how a suite runs the same tests under a different role or a different environment.test.describe.serialis 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
beforeAllis the exception, not the rule. The hook runs once for the file, and a test that mutates the shared state breaks the next test. ThebeforeEachreset is the safe pattern; thebeforeAllis 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.
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!