Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 35 ยท Structure and Maintainability

Hooks, Fixtures and Custom Commands

Reuse setup and teardown in browser tests: Cypress hooks and custom commands, Playwright fixtures, test.step and tags, with a runnable fixture engine.

After a handful of tests you start to see the same lines at the top of every one: visit the page, log in, create a record. Copying them works for a week and then hurts. When the login page changes, you edit twenty files. This lesson shows the tools both frameworks give you to share setup and teardown: hooks, custom commands (Cypress) and fixtures (Playwright).

The real tools cannot run on this site, so the Cypress and Playwright code below is read-only. The two runnable examples are stand-ins: a miniature hook runner and a miniature fixture engine written in plain Node.js. They show the mechanism, not the real implementation.

Hooks: code that runs around your tests

Both tools use the same four hooks as most JavaScript test runners:

Hook Runs Typical use
before / beforeAll once before all tests in a block start something expensive, seed shared read-only data
beforeEach before every test visit a page, log in, reset state
afterEach after every test, even a failed one clean up data created by the test
after / afterAll once after all tests in a block stop services, remove shared data

In Cypress they are global functions, and Mocha provides them:

JavaScript
// Cypress (read-only)
describe('account settings', () => {
  beforeEach(() => {
    cy.visit('/settings')
  })

  it('shows the current email', () => {
    cy.get('[data-cy=email]').should('have.value', '[email protected]')
  })

  it('lets the user change the name', () => {
    cy.get('[data-cy=name]').clear().type('Ada L.')
    cy.contains('button', 'Save').click()
    cy.contains('Saved').should('be.visible')
  })
})

In Playwright they hang off test:

TypeScript
// Playwright (read-only)
import { test, expect } from '@playwright/test';

test.describe('account settings', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });

  test('shows the current email', async ({ page }) => {
    await expect(page.getByLabel('Email')).toHaveValue('[email protected]');
  });
});

Notice that Playwright hooks receive the same { page } argument a test does. That argument is a fixture, and we come back to it below.

Two warnings apply to both tools. First, keep each test independent: it must pass when run alone, in any order. Hooks are the place to establish a state, not a place to carry state from one test to the next. Second, avoid long hooks that do many unrelated things. If a beforeEach is twenty lines, give it a name and move it into a command or fixture.

Cypress also clears cookies, local storage and session storage before each test by default (called test isolation). Playwright goes further: every test gets a brand-new browser context, so cookies and storage never leak between tests.

The next stand-in is a tiny runner with the four hooks. Watch the order of the output, and notice that afterEach still runs after a test that fails.

Node.js A miniature hook runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fourth test passes because afterEach emptied the list even though the third test threw. That is why cleanup belongs in an afterEach (or a fixture), never at the end of the test body, where a failure would skip it.

Cypress custom commands

When several tests need the same action, wrap it in a custom command. You register it once with Cypress.Commands.add in the support file, and it then appears on cy like any built-in command.

JavaScript
// cypress/support/commands.js (read-only)
Cypress.Commands.add('login', (email, password) => {
  cy.visit('/login')
  cy.get('[data-cy=email]').type(email)
  cy.get('[data-cy=password]').type(password, { log: false })
  cy.contains('button', 'Sign in').click()
  cy.url().should('include', '/dashboard')
})

// in a spec
it('shows the dashboard', () => {
  cy.login('[email protected]', 'correct horse')
  cy.contains('h1', 'Dashboard').should('be.visible')
})

The support file (cypress/support/e2e.js by default, set with e2e.supportFile in the config) is loaded before every spec. Put import './commands' there so the commands are registered. A few rules keep commands healthy:

  • Return Cypress chains, not promises; commands run through the queue explained in How Cypress Commands Really Work.
  • Prefer commands that do one thing and name them with a verb (login, addToCart).
  • For logging in quickly without the UI every time, wrap the steps in cy.session, covered in Test Data and Logging In Fast.
  • Cypress.Commands.overwrite can change a built-in command, but use it sparingly because it surprises readers.

Playwright fixtures

Playwright takes a different route. Instead of adding methods to a global object, it injects what a test needs through its first parameter. page is a fixture, so is context, and so is request. You can define your own with test.extend:

TypeScript
// fixtures.ts (read-only)
import { test as base, expect } from '@playwright/test';
import { SettingsPage } from './settings-page';

type Fixtures = {
  settingsPage: SettingsPage;
  account: { email: string };
};

export const test = base.extend<Fixtures>({
  account: async ({ request }, use) => {
    const res = await request.post('/api/test/accounts', { data: { name: 'Ada' } });
    const account = await res.json();
    await use(account);                       // the test runs here
    await request.delete('/api/test/accounts/' + account.id);   // teardown
  },

  settingsPage: async ({ page, account }, use) => {
    const settings = new SettingsPage(page);
    await settings.open();
    await use(settings);
  },
});

export { expect };
TypeScript
// settings.spec.ts (read-only)
import { test, expect } from './fixtures';

test('shows the account email', async ({ settingsPage, account }) => {
  await expect(settingsPage.emailField).toHaveValue(account.email);
});

The code before await use(...) is setup; the code after it is teardown, and it runs even when the test fails. Three properties make fixtures powerful:

  • On demand. A fixture is only created if a test (or another fixture) asks for it by name. A test that does not mention account never creates one.
  • Composable. The settingsPage fixture asked for account, so Playwright creates account first and tears it down last.
  • Scoped. By default a fixture is created per test. With { scope: 'worker' } it is created once per worker process, and { auto: true } makes it run for every test without being requested.

You can combine fixtures from several files with mergeTests.

The next stand-in is a small fixture engine. It reads which names a test asks for from its destructured parameter list, sets up each fixture and its dependencies in order, runs the test and tears down in reverse. Real Playwright does something very similar, though its implementation handles many more cases.

Node.js A miniature fixture engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the output, the first test creates only db. The second asks for loggedInPage, which pulls in user, which pulls in db: setup runs from the inside out and teardown in exactly the reverse order. The third fails with a clear message and still leaves nothing half-built.

Steps and tags in Playwright

Long tests become hard to read in a report. test.step groups actions under a name that appears in the HTML report and the trace:

TypeScript
// Playwright (read-only)
test('checkout', async ({ page }) => {
  await test.step('add item', async () => {
    await page.goto('/shop');
    await page.getByRole('button', { name: 'Add to cart' }).first().click();
  });
  await test.step('pay', async () => {
    await page.getByRole('link', { name: 'Cart' }).click();
    await page.getByRole('button', { name: 'Pay' }).click();
  });
});

Tags let you run a subset. In Playwright you pass them in the test details, then filter on the command line:

TypeScript
// Playwright (read-only)
test('user can sign in', { tag: ['@smoke', '@auth'] }, async ({ page }) => {
  // ...
});
Terminal
# read-only
npx playwright test --grep @smoke
npx playwright test --grep-invert @slow

Cypress has no built-in tag filter; teams add the @cypress/grep plugin and write it('signs in', { tags: '@smoke' }, ...). Check the plugin's documentation for the exact setup in your version.

flowchart TD
  A["Same setup in many tests"] --> B{"Which tool?"}
  B -->|"Cypress"| C["Custom command<br/>in support file"]
  B -->|"Playwright"| D["Fixture via<br/>test.extend"]
  A --> E["Only state reset needed"]
  E --> F["beforeEach / afterEach"]

Hooks reset state, commands and fixtures package reusable setup.

Choosing between them

Use a beforeEach when the setup is small and every test in one block needs it. Reach for a custom command or fixture when the setup is shared across files, takes parameters, or needs cleanup that must always run. Do not hide assertions inside commands or fixtures unless the name says so (assertLoggedIn); a reader should be able to see what a test checks. The next lesson, Page Objects and Better Test Structure, applies the same thinking to whole pages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should cleanup code live so it still runs when a test fails?

    A failing assertion throws and skips the rest of the test body. Hooks and fixture teardown run regardless.
  2. 2. What does a Playwright fixture do when a test never mentions it by name?

    Fixtures are lazy. Only fixtures a test or another fixture requests are set up, apart from those marked auto: true.
  3. 3. Which line registers a reusable login action in Cypress?

    Cypress.Commands.add, normally called in the support file, adds a new command to cy.
  4. 4. What is the main benefit of test.step?

    Steps do not change behavior. They only label parts of a test so reports and traces are easier to read.

Summary

  • Hooks (before, beforeEach, afterEach, after) establish and clean up state around tests; keep every test independent.
  • Cypress shares actions with Cypress.Commands.add in the support file.
  • Playwright shares setup with fixtures from test.extend: code before use is setup, code after it is teardown.
  • Fixtures are lazy, composable and can be scoped per worker or run automatically.
  • test.step labels parts of a long test, and tags with --grep run a subset.
  • Do not hide assertions inside helpers unless their names say so.

Next: Page Objects and Better Test Structure