Three tests are green, one is red, and one account on the site was never deleted. Run this suite on CI every day and every red run leaves one more account nobody cleans up. This lesson writes the same four tests four times, until the cleanup cannot be forgotten, and gives you one question: who cleans up when the test fails? It follows the official docs (Fixtures, Test hooks), and every command and output comes from a real run.

What you need

  • Node.js. 22, 24, 26.
  • Playwright 1.65.1. The lesson was recorded with this version; other versions may print slightly different output.
  • The code. Subscribers see the lesson repository in the Source code box under the video, with the tags pw05-start and pw05-end.

The tests create and delete real accounts on automationexercise.com through the site's own API. A helper, tests/helpers/account.ts, has createAccount, deleteAccount and login, and prints one line per call: a plus line for a created account and a minus line for a deleted one. The site sometimes shows a waiting page to automated browsers, so a test can time out; run it again a little later. Times are not the point of this lesson and will differ on your machine.

Step 1: Three green, one red, one account left

The four tests are header shows name, cart is empty, logout works and home has title. One word is mistyped on purpose in cart is empty: it waits for Your cart is empty, but the real page says Cart is empty!.

Step 2: Version one, copy the prep into every test

tests/before.spec.ts is how everyone starts: each test creates its own account, logs in, runs its check, and deletes the account on the last line.

npx playwright test tests/before.spec.ts --project=site --workers=1

Fails on purpose. cart is empty is red by design.

The log shows plus, minus, plus and then no minus: the red test created an account and never deleted it. Ask the site directly and it answers User exists!. The reason is simple: a test runs from top to bottom, and expect waits 5 seconds (the docs say auto-retrying assertions like toHaveText have their own timeout, 5 seconds by default, unrelated to the test timeout), finds no text and throws. Once it throws, the test stops, so the last line never gets its turn. If a red run is new to you, lesson 4 shows how to read one.

Step 3: Version two, beforeEach and afterEach

Playwright has places for exactly this, called hooks. test.beforeEach runs before each test and test.afterEach runs after each test; the docs say to use afterEach to tear down what beforeEach set up.

let acc: Account;

test.beforeEach(async ({ page, request }) => {
  acc = await createAccount(request);
  await login(page, acc);
});

test.afterEach(async ({ request }) => {
  await deleteAccount(request, acc);
});
npx playwright test tests/hooks.spec.ts --project=site --workers=1

Now the red test gets its minus line too: afterEach runs even when the test fails. Four pluses, four minuses. But four? Only three tests need a login. home has title only reads the page title, yet it gets an account and a login too, so it is slower than in version one. beforeEach does not ask what a test needs: it runs for every test in its scope. The let variable is a drop-off between the separate hook functions.

Step 4: Version three, beforeAll and afterAll

test.beforeAll runs once before all tests and test.afterAll once at the end: one account, one login, shared by the whole file.

let acc: Account;
let page: Page;

test.beforeAll(async ({ browser, request }) => {
  acc = await createAccount(request);
  page = await browser.newPage();
  await login(page, acc);
});

beforeAll cannot receive page: in the docs' table of built-in fixtures, page is an isolated page for this test run, and beforeAll runs before any test run exists. So you open a page yourself with browser.newPage() and keep it in a second let.

npx playwright test tests/before-all.spec.ts --project=site --workers=1

The first test is fast, because the login already happened. After the red test, beforeAll prints a second time. The reason is the worker: tests run in a process called a worker, and when a test fails Playwright drops that worker and starts a new one. The docs say it: the worker process is restarted on test failures, and the beforeAll hook runs again in the new worker. afterAll ran twice as well, so nothing was left behind this time.

The shared page has another cost. In tests/shared-page.spec.ts, the logout test runs before the header test:

npx playwright test tests/shared-page.spec.ts --project=site --workers=1

The logout test clicks Logout on the shared page, so the header test that runs next sees a logged-out page and fails. It did nothing wrong; it ran after another test. Fast, but the tests are tangled.

Fails on purpose. shared-page.spec.ts is red by design.

Step 5: Version four, a fixture

What do we want? Prepare exactly what a test needs, clean up right after, even when it fails, and no let at the top of the file. The fixtures page lists these benefits: setup and teardown in the same place, reusable between test files, on-demand, and composable.

tests/fixtures.ts calls test.extend, which takes an object where each key is a fixture. Each function has three parts:

export const test = base.extend<{ account: Account; userPage: Page }>({
  account: async ({ request }, use) => {
    const acc = await createAccount(request);   // set up
    await use(acc);                             // the test runs here
    await deleteAccount(request, acc);          // tear down, green or red
  },
  userPage: async ({ page, account }, use) => {
    await login(page, account);
    await use(page);
  },
});

Everything above await use is setup, everything below is teardown. userPage asks for two things, the built-in page and our account: fixtures stack on each other, which the docs call composable. account in turn needs request, to call the API.

tests/fixture.spec.ts asks for userPage by name:

npx playwright test tests/fixture.spec.ts --project=site --workers=1

Playwright builds account first, then userPage, runs the test, and when the test ends (green or red) unwinds in reverse: the delete line runs last. Three pluses, three minuses for four tests. The red test's account is created and then deleted; ask the site and it says User not found!. home has title only asks for page, so nothing is built for it: not named, not built.

Two things to know. The time a fixture takes to set up and tear down counts towards the test timeout, so a slow fixture can time out a test whose body is fast; the docs let you set a separate timeout for it. And lesson 6 renames these two files to fixtures-account.ts and fixture-account.spec.ts to make room for its own; at pw05-end they have the names used here.

Step 6: In what order does it run?

Hooks do not go away, so you will meet files that have both. tests/order.spec.ts has four hooks, a fixture called cart and two tests that print their own names:

npx playwright test tests/order.spec.ts --project=site --workers=1
OrderWhat prints
1beforeAll
2beforeEach
3cart setup (the fixture, lazily)
4the test, then afterEach
5cart teardown

afterAll sits at the very end, and second does not ask for cart, so it has no cart lines. The docs call this execution order: non-automatic fixtures are executed lazily, only when the test or hook needs them. There is one more scope, the worker scope ({ scope: 'worker' }), which sets a fixture up once per worker process. But after a failed test the worker is replaced, so a worker-scoped fixture is built again from scratch, like beforeAll (tests/worker-fixture.spec.ts).

Step 7: Where does each thing go?

UseWhen
Inline in the testone test, nothing to clean up
beforeEachevery test needs the same step and nothing needs cleaning, like opening one page
beforeAllsomething expensive and read-only that no test changes (it still runs again after a failure)
Fixturesomething to clean up, or only some tests need it

A rule of thumb: when it repeats a third time, or something needs cleaning, pull it out.

Tests that fail on purpose

FileFails because
before.spec.ts, hooks.spec.ts, before-all.spec.ts, fixture.spec.tscart is empty waits for the wrong text
shared-page.spec.tsheader shows name runs after logout works
worker-fixture.spec.tsthe second test expects the wrong name

Check your result

  • npx playwright test tests/fixture.spec.ts --project=site --workers=1 → 1 failed, 3 passed, and every plus line has a minus line
  • npx playwright test tests/order.spec.ts --project=site --workers=1 → 2 passed

Recap

VersionLeaves an account?Preps tests that do not need it?Tests tangled?
1. Copyyesnono
2. beforeEachnoyesno
3. beforeAllnonoyes
4. Fixturenonono
  1. A line after a failed expect never runs; cleanup belongs in a hook or a fixture.
  2. beforeEach runs for every test; a fixture is built only when a test names it.
  3. After a failed test the worker restarts, so beforeAll runs again.
  4. Code above await use is setup, below it is teardown.

Next lesson

userPage only knows how to log in. Next, we gather the locators for add to cart, view cart and checkout into a Page Object and plug it into this fixture.