QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Fixtures and test structure

Fixtures and scopes

A Playwright fixture is a dependency a test asks for in its parameters; the runner creates it, hands it over and cleans it up. The code before await use() is setup and the code after it is teardown, which runs even when the test fails. Fixtures are created lazily. The test scope isolates each test, while worker creates one fixture per worker and cannot depend on test fixtures such as page.

Playwright · Fixtures

A test created an order and failed on an assertion. Who deletes the order now?

A test creates an order through the API, checks the page and deletes the order at the end. The assertion failed, the line with the deletion never ran, and a "garbage" order stayed in the database. After fifty runs the database is full of such records, and later tests start failing on searches or counters. Playwright fixtures exist for exactly this: cleanup always runs, and it lives right next to the setup.

How it works and why. The usual approach, beforeEach plus shared variables, has three flaws: the setup runs for every test of the block even when a test does not need it; the cleanup lives somewhere else (in afterEach or at the end of the test) and easily drifts away from the setup; and there is a hidden coupling between the hook and the test through a variable. Fixtures solve this as dependency injection: a test declares what it needs in the destructured first parameter ({ page, loginPage }), and the runner creates those objects, hands them to the test and cleans them up. The built-in page, context and request are built the same way; test.extend adds your own.

A fixture is a function of three parts: the code before await use(value) is the setup, the value passed to use goes to the test, and the code after it is the teardown. The key property: after use the runner always returns control, even when the test failed, so the teardown is not skipped. Fixtures are created lazily, only if a test (or another fixture) asked for them; they can depend on each other: a dependency is always set up before, and torn down after, the fixture that uses it.

The fixture lifecycle

setup: code before use await use(value) the test body gets value test passed test failed teardown: code after use, always test scope: the whole cycle for every testworker scope: once per worker, teardown at the end
Figure 1. The teardown runs in both branches. The scope only decides how many times this cycle goes round.
import { test as base, expect } from '@playwright/test';
import { LoginPage } from './pages/login-page';

type Fixtures = { loginPage: LoginPage };

export const test = base.extend<Fixtures>({
  loginPage: async ({ page }, use) => {
    const loginPage = new LoginPage(page); // setup
    await loginPage.goto();
    await use(loginPage); // the test runs here
    // teardown: after await use(), even if the test failed
  },
});
export { expect };

// a test asks for the fixture by name, nothing else is created
test('login with a valid password', async ({ loginPage }) => {
  await loginPage.signIn('qa@example.com', 'Secret123');
});

The test names the fixture in its parameters, and nothing else is created. If, for instance, a test does not ask for loginPage, the login page is not opened for it.

Example: before → after. The test from the start of the article, built with a hook and a variable:

let orderId: string;

test.beforeEach(async ({ request }) => {
  const res = await request.post('/api/orders', { data: { items: [{ sku: 'A1', qty: 1 }] } });
  orderId = (await res.json()).id;
});

test('order page shows the status', async ({ page, request }) => {
  await page.goto('/orders/' + orderId);
  await expect(page.getByTestId('order-status')).toHaveText('New'); // fails here
  await request.delete('/api/orders/' + orderId); // never reached
});
Error: expect(locator).toHaveText(expected)
Expected: "New"
Received: "Created"

How to read it. The error is real: the page shows another status. But there is a second harm the log does not show: execution stopped at the assertion, so delete never ran and the order stayed. This is not bad luck but a property of the code: everything after a failed assertion does not run. In addition, beforeEach creates an order for every test of the block, and the orderId variable couples the hook and the test implicitly.

The fix: move both parts into a fixture.

The order fixture: three phases

type Order = { id: string };

export const test = base.extend<{ order: Order }>({
  // depends on the built-in request fixture
  order: async ({ request }, use) => {
1    const res = await request.post('/api/orders', { data: { items: [{ sku: 'A1', qty: 1 }] } });
    const order = (await res.json()) as Order;
2    await use(order);
3    await request.delete('/api/orders/' + order.id); // cleanup also after a failed test
  },
});

test('order page shows the status', async ({ page, order }) => {
  await page.goto('/orders/' + order.id);
  await expect(page.getByTestId('order-status')).toHaveText('New');
});
  1. Setup: runs before the test. The order is created through the API, not the UI.
  2. use(): the test itself runs here and receives order as a parameter.
  3. Teardown: runs after the test, even if it failed. That is why the cleanup lives here and not at the end of the test.
Figure 2. The number stands in for the line number: the three phases of a fixture.

Now the deletion sits after use, and the runner calls it regardless of the test result. The order is created only for the tests that wrote order in their parameters, and the dependency is visible in the signature. The temptation to "wrap the test body in try/finally" works for one test only and gets copied into all the others, while a fixture is written once.

A hook with a variable or a fixture

Typical

beforeEach + a shared variable

Setup for every test of the block, cleanup at the end of the test, skipped after a failure. The coupling through a variable is hidden, and the code gets copied between files.

Better

A fixture

Created only on request. The teardown sits next to the setup and runs after a failure. The dependency is visible in the test parameters, one declaration for the whole project.

Figure 3. The difference is not the convenience of the syntax but what the runner guarantees.

The second typical case is a fixture with a ready Page Object (see the loginPage example above): the test gets the object at once, without new and goto.

Scopes. There are two. test (the default): the fixture is created for every test separately, which is isolation at the price of time. worker: one per worker, for all of its tests, which pays off for expensive things: a database connection, starting a helper service, a test user. The scope is given in the options object, the second element of an array whose first element is the function itself. In base.extend<TestFixtures, WorkerFixtures> the first type argument describes test fixtures and the second one worker fixtures.

import { test as base } from '@playwright/test';
import { connect, type Db } from './db';

export const test = base.extend<{}, { db: Db }>({
  // an array: [function, options]
  db: [
    async ({}, use, workerInfo) => {
      const db = await connect({ schema: 'w' + workerInfo.workerIndex });
      await use(db); // one connection for all tests of this worker
      await db.close();
    },
    { scope: 'worker' },
  ],
});
test (default)worker
When it is createdfor every testonce per worker, on the first request
Isolationfullshared by the tests of a worker
FitsPage Object, test data, pageDB connection, expensive setup
May depend ontest and worker fixturesworker fixtures only

The reason for the last row: a worker fixture lives longer than any test, while page is created and closed for every test, so the worker fixture cannot depend on it. There are several workers, and a worker fixture is created in each of them separately, so for unique data use workerInfo.workerIndex or parallelIndex, otherwise workers fight over the same resources. After a failed test the worker is restarted, and worker fixtures are created again.

Limits and alternatives.

  • The code after use runs only if execution reached use. If the setup threw midway (two resources created, the third failed), cleaning up what already exists is on you: try/finally inside the fixture.
  • A fixture for a single test is excessive: a one-off setup is simpler to keep in the test body.
  • Fixtures do not make tests independent by themselves: a worker fixture with mutable state ties tests together by order again.
  • Cypress has no injection: setup goes into beforeEach, custom commands or cy.task, and there is no guaranteed setup and teardown pair. In JUnit 5 these are @BeforeEach and @AfterEach, in TestNG @BeforeMethod and @AfterMethod; the closest analogy by idea is pytest fixtures with yield.

Common mistakes.

  • A worker fixture that depends on page or request (test-scoped): Playwright throws an error, because the worker outlives the test.
  • Shared mutable state in a worker fixture: one test changes the object, the next one sees the changes, and the result depends on order.
  • Cleaning data at the end of the test instead of in the fixture teardown: it does not run after a failure, and garbage piles up in the DB.
  • Heavy setup in test scope when worker scope would do: the suite slows down for nothing.
  • A beforeEach copy-pasted into ten files instead of one fixture: a fix in one place does not reach the rest.

Check yourself

The order fixture creates an order with POST and deletes it after use. The test failed on expect. Will the order be deleted? And what if the POST itself failed?

Answer

In the first case yes: the code after use runs regardless of the test result. If the POST itself failed, the fixture never reached use, so its code after use does not run, but there is nothing to delete either, since the order was not created. The dangerous case: several resources were created and a later step failed, then try/finally cleans up what was created earlier.

The worker fixture db asks for { page } in its parameters. What happens and why?

Answer

Playwright rejects such a dependency with an error: page is test-scoped and is created for every test, while a worker fixture lives for the whole life of the worker and cannot depend on an object that appears and disappears between tests.

A test asks for { page } but not for the order fixture you declared in test.extend. Will the order be created?

Answer

No. Fixtures are created lazily, only when a test or another fixture asks for them. The exception is auto fixtures with auto: true, which start for every test (covered in the lesson "Fixtures in depth").

In an interview. Junior: Fixtures are dependency injection: a test asks for { page, order }, and the runner creates them and cleans up after the test. Middle/Senior: The main advantage: the teardown after use runs even when the test failed, so data does not pile up. Fixtures are created lazily, unlike beforeEach, which runs for every test of the block. I make cheap and isolated things test-scoped and expensive ones (a DB connection) worker-scoped with unique data by workerIndex, remembering that a worker fixture cannot depend on page.

More articles in this chapter