What is the significance of beforeAll and afterAll hooks in Playwright?
test.beforeAll() runs once before the tests in its file or describe block, and test.afterAll() runs once after them. They are for expensive setup and cleanup that many tests can share: seeding a test database, creating a test user through an API, starting a mock server. The catch, and the part interviewers like to probe, is what "once" really means in Playwright.
A working example
// tests/batch.spec.ts
import { test, expect } from '@playwright/test';
let batchId: string;
test.beforeAll(async ({ request }) => {
// create shared test data once, through the API
const res = await request.post('/api/test/batches', { data: { name: 'Weekend batch' } });
expect(res.ok()).toBeTruthy();
batchId = (await res.json()).id;
});
test.afterAll(async ({ request }) => {
await request.delete(`/api/test/batches/${batchId}`);
});
test('batch page shows the name', async ({ page }) => {
await page.goto(`/batches/${batchId}`);
await expect(page.getByRole('heading', { name: 'Weekend batch' })).toBeVisible();
});
test('student can join the batch', async ({ page }) => {
await page.goto(`/batches/${batchId}`);
await page.getByRole('button', { name: 'Join' }).click();
await expect(page.getByText('You have joined')).toBeVisible();
});
The endpoints are placeholders. The pattern is what matters: shared data is created by the API, not by clicking through the UI, and it is removed in afterAll.
The order hooks run in
With one beforeAll, one beforeEach, one afterAll and three tests in a file, a run on one worker prints:
beforeAll
beforeEach → test a
beforeEach → test b
beforeEach → test c
afterAll
beforeEach and afterEach wrap every test; the "All" hooks wrap the whole group. Hooks declared inside a test.describe() apply only to that block.
"Once" means once per worker
Playwright runs tests in worker processes, and hooks belong to the worker. Two consequences follow:
- Parallel tests repeat the hook. If a file's tests are spread across several workers (with
fullyParallel: true), each worker runsbeforeAllfor itself. Your seed code must cope with running more than once, for example by using unique names. - A failure restarts the worker. When a test fails, Playwright throws that worker away and continues in a new one, which runs
beforeAllagain. In a quick run of three tests where the middle one failed, the log showedafterAllafter the failure, thenbeforeAllagain on worker 1 before the third test.
More on workers in parallelism in Playwright.
Why you cannot use page in beforeAll
A common first attempt is test.beforeAll(async ({ page }) => { ... }). It fails with:
Error: "context" and "page" fixtures are not supported in "beforeAll"
since they are created on a per-test basis.
Each test gets its own page so tests stay isolated (see browser isolation). In beforeAll you can use worker-level fixtures such as browser and request. To log in once, save a storageState file in a setup project instead; see authentication in Playwright tests.
Better tools for some jobs
| Need | Use |
|---|---|
| Setup shared by every file (log in, seed DB once per run) | A setup project with dependencies, or globalSetup |
| Reusable setup that tests ask for by name | A custom fixture; see fixtures in Playwright |
| Fresh state before every test | beforeEach |
| Setup for one file's tests only | beforeAll |
Gotchas
- If
beforeAllthrows, every test in that group is reported as failed or skipped, so keep the hook small and the error message clear. - Hooks have their own timeout, equal to the test timeout by default. Slow seeding can use
test.setTimeout()inside the hook. - Variables assigned in
beforeAllare per worker. Do not expect another worker to see them.
Want to master Playwright hands-on?
Join Uncodemy's Playwright Automation Testing Course in Noida — Dedicated Placement Support.
Explore the Course →