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;
}>({
  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,
    );
  },
});

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 numbers mark the three phases of a fixture, not code line numbers.

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.

Hooks, describe and conditional tests

Hooks are tied to the worker and the test group: beforeAll and afterAll run once per worker for a file or a test.describe, without page. beforeEach and afterEach run around every test. For a known bug use test.fail() rather than test.skip(): the test still runs and reports by itself when the bug is fixed, whereas skip silently hides the lost coverage. A quick subset is chosen with tags and --grep.

Playwright · Fixtures

The bug is known, the ticket exists, and the test goes red every day. Skip, fixme or fail?

A suite grows, and so do the questions. Where should state be prepared before a test? What to do with a test that runs into a known bug, so that it neither breaks CI nor gets lost? How to run only the quick part of the suite? The answers come from describe, hooks, execution annotations and tags. This lesson covers what each of them guarantees, where it lets you down and when a fixture is the better choice.

How hooks work and why. test.describe only groups tests: a shared title in the report, shared hooks, shared options. Hooks are tied to the worker lifecycle. beforeAll and afterAll run once per worker, so only worker fixtures are available there (browser, playwright), and page is not: it does not exist yet. beforeEach and afterEach run around every test and have the same fixtures as the test, page included. The practical rule follows: anything that needs a page lives in beforeEach.

The order of hooks around a test

beforeAll beforeEach test afterEach for everytest afterAll: once per worker, at the end once per worker
Figure 1. The bracket on the right repeats for every test, while beforeAll and afterAll run once per worker.
test.describe('Transfers', () => {
  test.beforeAll(async () => {
    // once per worker: only worker fixtures here, no page
  });

  test.beforeEach(async ({ page }) => {
    await page.goto('/transfers'); // before every test
  });

  test.afterEach(async ({ page }, testInfo) => {
    if (testInfo.status !== testInfo.expectedStatus) {
      await testInfo.attach('url', { body: page.url() }); // also after a failure
    }
  });

  test('shows the daily limit', async ({ page }) => {
    await expect(page.getByTestId('daily-limit')).toBeVisible();
  });
});

In nested describe blocks the outer block's beforeEach runs first, then the inner one. afterEach also runs after a failed test, so diagnostics are collected there by testInfo.status. Hooks can be titled: test.beforeEach('login', …), and then they appear in the report as a separate step. There is a subtlety too: after a failed test Playwright restarts the worker, so beforeAll runs again in the new process, and module-level variables it filled are empty in the new worker.

Hook or fixture. A hook is simpler and more visible within a single file. A fixture is better when the logic repeats across many files, when a guaranteed teardown next to the setup is needed, and when the preparation should run only for the tests that asked for it (a hook runs for every test of the block). Hooks easily create a hidden coupling through module variables, while a fixture shows the dependency in the test signature.

Example: before → after. A test runs into a known bug and was "switched off":

test.skip('rounding of the commission', async ({ page }) => {
  await page.goto('/fees');
  await expect(page.getByTestId('fee')).toHaveText('1.25');
});

This works exactly as long as someone remembers the test. The bug gets fixed, the test stays skipped: coverage was lost silently and nobody learns about it. The fix: keep the test active and tell the runner that it must fail.

test('rounding of the commission', async ({ page }) => {
  test.fail(true, 'Known bug PAY-731: rounds down');
  await page.goto('/fees');
  await expect(page.getByTestId('fee')).toHaveText('1.25');
});

Now the runner executes the test and expects a failure. While the bug exists, the test counts as passed (an expected failure) and does not turn CI red. As soon as the bug is fixed, the test starts passing, and the runner reports that a failure was expected: the signal arrives by itself, without reminders in a ticket.

A known bug: skip or fail

Typical

test.skip

The test does not run. When the bug is fixed, nobody notices, and coverage has quietly gone. It fits environment conditions, not bugs.

Better

test.fail with a reason

The test runs and fails as expected. When the bug disappears, the runner itself reports that a failure was expected. The ticket number in the reason leads to the context.

Figure 2. A known bug must not hide a test: you need a mechanism that reminds you of it.

Controlling execution. test.skip(condition, 'reason') skips by a condition, for example for a browser or platform; a callback with fixtures also works for a whole file or block. test.fixme() marks a test that is known to be broken and does not run it: a "needs fixing" marker, suitable when running it is slow or crashes the process. test.fail() runs the test and expects a failure. test.slow() triples the timeout for this test.

test('export to PDF', async ({ page, browserName }) => {
  test.skip(browserName === 'webkit', 'Bug PAY-512 in WebKit'); // by a condition
  await page.goto('/reports');
});

// a whole file or describe block: a callback with fixtures
test.skip(({ isMobile }) => isMobile, 'The desktop layout only');

test('large import', async ({ page }) => {
  test.slow(); // timeout x3, for this test only
  await page.goto('/import');
});

Tags and annotations. A tag is set in the test or block details ({ tag: '@smoke' }) or directly in the title, and it must start with @. Filter with --grep and --grep-invert, both accept regular expressions. Annotations (annotation: { type, description }) do not affect the run but show up in the HTML report, so they are handy for ticket links. Tags let you pick a quick set for CI without splitting tests into files.

test('quick search', { tag: ['@smoke', '@search'] }, async ({ page }) => {
  await page.goto('/search');
});

test.describe('Payments', { tag: '@payments' }, () => {
  test(
    'card payment',
    { annotation: { type: 'issue', description: 'PAY-512' } },
    async ({ page }) => {
      await page.goto('/pay');
    },
  );
});
npx playwright test --grep @smoke
npx playwright test --grep-invert "@slow|@flaky"
npx playwright test --grep "(?=.*@smoke)(?=.*@search)"   # both tags

Limits and alternatives. A tag is just a string nobody validates: a test with a typo in its tag (@smok) silently drops out of the filtered run, so keep the list of tags in one place. beforeAll is not suitable for data that tests modify one after another, because the order and the parallel workers make the result unpredictable. Cypress has no native tags: selective runs are done with the @cypress/grep plugin; in the Selenium stack these are JUnit/TestNG categories or tags.

Common mistakes.

  • test.skip for a known bug instead of test.fail or test.fixme: the gap stays unnoticed and nobody learns about the fix.
  • Trying to take page in beforeAll: the fixture is test-scoped and unavailable there.
  • Order dependence: beforeAll prepares data that tests modify one after another.
  • A conditional if (browserName === …) return inside a test instead of test.skip: the test "passes" with no checks at all, and the report does not show it.
  • Root-level hooks for logic that only some tests need: it runs for all of them, including those that do not need it.

Check yourself

You write await page.goto('/') in beforeAll and get an error. Why, and where should the line go?

Answer

beforeAll runs once per worker, while page is test-scoped and created for every test, so it is not there. Navigation moves to beforeEach. If an expensive shared setup really is needed once per worker, a worker fixture is used for it.

A test with a known bug was marked test.fail(). A month later the bug was fixed. What will the team see after a run?

Answer

The test starts passing, and the runner treats that as an error because a failure was expected: the run turns red with a message about it. Then the annotation is removed and the test works as a normal one again. With test.skip the run would stay green while the test never ran.

In an interview. Junior: beforeEach runs before every test and has access to page, while beforeAll runs once per worker without page. Tests that should not run are skipped with test.skip. Middle/Senior: For a known bug I take test.fail with a ticket number, because the test itself tells when the bug is fixed, whereas skip hides the loss of coverage. I move repeated setup with teardown into fixtures, and pick the quick CI set with tags and --grep.

test.step and the describe.configure modes

test.step wraps part of a test in a named block, so the report and trace show a tree of business steps instead of a flat list of actions. The test.describe.configure modes control distribution: by default tests of a file run in order, parallel spreads them across workers, and serial binds the group: after a failure the rest is skipped and a retry restarts the group. Serial suits only inseparable scenarios.

Playwright · Fixtures

The report shows fifty clicks and requests. At which step did the order break?

An order checkout test failed, and you open the report. It is a flat list: click, fill, click, wait, another click. To tell whether payment or the status check broke, you have to read lines of code. A second pain of the same kind: the tests of a file are independent but run one after another in a single worker, so the run is long, or the opposite, they were made dependent and one failure cancels the rest. This lesson covers two tools: test.step makes the report readable, and test.describe.configure controls how tests are distributed across workers.

How test.step works and why. A step wraps part of a test in a named block. In the HTML report and trace, instead of a flat list of actions you get a tree of business steps: "Place the order", "Pay", "Check the status". Steps can be nested, a step returns the value from its callback, and if an assertion fails inside, the step is marked as failed and the error is attached to it. This does not change the test logic: a step only adds structure to the report. The scenario reads like a specification.

The same failed test in a report

Typical

Without steps

A flat list of dozens of actions. To tell which business action broke, you read the test code line by line.

Better

With test.step

A tree: "Place the order", "Pay" (with a nested "Enter the card"), "Check the status". The red step shows the stage at once.

Figure 1. Steps add no checks: they only group actions so that the report reads like a scenario.
test('purchase', async ({ page }) => {
  const orderId = await test.step('Place the order', async () => {
    await page.getByRole('button', { name: 'Buy' }).click();
    return page.getByTestId('order-id').innerText();
  });

  await test.step('Pay', async () => {
    await test.step('Enter the card', async () => {
      await page.getByLabel('Card number').fill('4242424242424242');
    });
    await page.getByRole('button', { name: 'Pay' }).click();
  });

  await test.step('Check the status', async () => {
    await expect(page.getByText('Order ' + orderId)).toBeVisible();
  });
});

Steps are convenient to wrap in Page Object methods, so that every business action shows up in the report as one line. The { box: true } option "boxes" the step: the error points to the step call in the test, not to the line inside the helper. This reads better when the helper is called from many tests.

import { expect, test, type Page } from '@playwright/test';

export class CheckoutPage {
  constructor(private readonly page: Page) {}

  async pay(card: string) {
    await test.step(
      'Pay by card',
      async () => {
        await this.page.getByLabel('Card number').fill(card);
        await this.page.getByRole('button', { name: 'Pay' }).click();
        await expect(this.page.getByText('Payment accepted')).toBeVisible();
      },
      { box: true }, // a failure points at checkout.pay(...) in the test, not at this line
    );
  }
}

The limit of reason: a step per click makes the report longer than the test itself. A step should match an action the business would name: "Pay", not "Click the button".

describe.configure modes. By default different files run in parallel across workers, while tests inside a file run in order in one worker. A failed test does not cancel the others: the worker is restarted and the following tests go on in the new one. The mode can be changed at file or block level.

ModeBehaviorWhen
defaulttests of a file sequentially in one worker; a failure does not cancel the othersthe usual case, files are independent
paralleltests of the block are distributed across workerstests share no data and order does not matter
serialsequentially; after a failure the rest is skipped, and on a retry the whole group restarts together with beforeAlla long dependent scenario, an exception

In parallel mode the tests of a group may land in different workers, so each test runs its own beforeAll and afterAll, and sharing variables between tests will not work. Serial mode does the opposite and binds the group into one dependent sequence:

Serial: a failure and a retry

test 1: passed test 2: failed test 3: skipped retry:the whole groupfrom test 1 default: a failure does not cancel other testsserial: after a failure the rest is skipped
Figure 2. The price of serial: skipped tests and a repeat of the whole chain on a retry.
// the whole file: tests run in parallel in different workers
test.describe.configure({ mode: 'parallel' });

test.describe('Registration wizard', () => {
  // one long scenario: steps depend on each other
  test.describe.configure({ mode: 'serial', retries: 1, timeout: 90_000 });

  let page: Page;
  test.beforeAll(async ({ browser }) => {
    page = await browser.newPage(); // one page for the whole chain
  });
  test.afterAll(async () => {
    await page.close();
  });

  test('step 1: personal data', async () => {
    await page.goto('/signup');
  });
  test('step 2: documents', async () => {
    // skipped if step 1 failed; on a retry the group starts from step 1
  });
});

Through configure you can also set retries and timeout for a group. The global fullyParallel: true in the config equals the parallel mode for all files. Serial mode is not a replacement for workers: 1: it only binds the tests of the group, while other files still run in parallel.

// playwright.config.ts
export default defineConfig({
  fullyParallel: true, // = mode 'parallel' for all files
  workers: process.env.CI ? 4 : undefined,
});

Example: before → after. A registration wizard was made serial with two steps, and the first step sometimes fails on a slow environment. Consequence: the second test is skipped, the report shows one red and one grey, and a retry reruns both. The fix follows the rule "a test starts from the needed state": the second test does not depend on the first, and the preparation (a draft application) is created by a fixture through the API. Then a failure of the first step does not mask the second, each test can be run alone with --grep, and parallel mode lets them run at the same time.

Limits and alternatives. Serial stays an exception for truly indivisible scenarios: a test cannot be run alone, a failure of the first step skips the rest, and a retry repeats the chain entirely. For saving time on login serial is not needed: it breaks isolation, and the saving is delivered by storageState. Steps are not assertions: a step with actions and no checks will be "green". Cypress has no built-in steps with a tree in the report, usually cy.log is used, and a sequence of it blocks in a file also ties tests by order there, so the same risks of dependent tests remain.

Common mistakes.

  • A step per click: the report becomes noisy and grouping gives no value.
  • serial "to save time" on login: it breaks isolation, and the saving is delivered by storageState.
  • parallel for tests that change a shared DB record: flakiness appears.
  • Expecting beforeAll in a serial group to run once: on a retry it starts again.
  • A step with actions and no assertions: it is "green" although nothing was checked.

Check yourself

In a serial group of three tests the second failed. Which tests run on the retry if retries: 1?

Answer

The group repeats entirely: from the first test and with a new run of beforeAll. The third test was skipped on the first attempt, and on the retry it runs if the second passes. That is why expensive steps in a serial group get repeated, and the tool suits only truly indivisible scenarios.

The pay() helper is wrapped in test.step without box, and an assertion inside failed. Where does the error point in the report, and what changes with box: true?

Answer

Without box the error points to the assertion line inside the helper. With box: true it points to the checkout.pay(...) call in the test, the place where the scenario turned to the step. This is handy for helpers called from many tests.

In an interview. Junior: test.step divides a test into named steps, and the report shows at which stage it failed. Middle/Senior: I make steps at the level of business actions and wrap Page Object methods in them with box: true. I rarely use serial mode: on a retry it restarts the whole group, and a single test cannot be run alone. Instead I make tests independent, prepare data through the API or a fixture, and enable parallel for files where tests do not share state.

Fixtures in depth: worker, auto, option, mergeTests

Fixture kinds differ in when they are created and who starts them. A test fixture is created on request of a test, a worker fixture once per worker (workerIndex gives unique data), an auto fixture with auto: true runs without being mentioned, and an option fixture is a parameter set in the config or via test.use. A large set is split into modules and assembled with mergeTests.

Playwright · Fixtures

Five workers log in as one account and wipe each other's cart. How to keep them apart?

Locally the suite is green, but on CI with five workers tests fail at random: the cart is empty although an item was just added, or the order is "someone else's". All workers sign in to the app under one test account and change shared state. The basic fixtures with test and worker scopes do not fully solve this. Here: a worker fixture with unique data, auto fixtures, option fixtures, overriding built-ins and assembling modules through mergeTests.

How it works and why. Fixtures differ in when they are created and who starts them. A test fixture is created on request of every test. A worker fixture is created once per worker, and workerInfo.workerIndex gives it a unique number: so the expensive setup runs once, while data does not overlap between workers. An auto fixture starts without being mentioned in the test. An option fixture is a parameter with a default value, changed in the config or through test.use. The runner arranges the creation order from the dependencies itself, so all of these combine.

One account or an account per worker

Typical

One account for all

Parallel tests change a shared cart and profile. Failures are random and vanish when the tests run one by one.

Better

A worker fixture

Each worker creates its own user once and deletes it at the end. Data does not overlap, and the setup is not repeated for every test.

Figure 1. Parallelism is safe only when workers do not share mutable state.

Example: before → after. This is a login that knows nothing about workers:

test.beforeEach(async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('qa@test.com'); // the same account everywhere
  await page.getByLabel('Password').fill('Secret123');
  await page.getByRole('button', { name: 'Sign in' }).click();
});

All tests of all workers hold the same account: someone emptied the cart, someone changed the profile language, and another test sees the result. The symptom is typical: tests pass alone and fail together. The fix: an account per worker.

import { test as base } from '@playwright/test';

type WorkerFixtures = { account: { email: string; password: string } };

export const test = base.extend<{}, WorkerFixtures>({
  account: [
    async ({ playwright }, use, workerInfo) => {
      // request and page are test-scoped, so a worker fixture builds its own API context
      const api = await playwright.request.newContext({ baseURL: process.env.API_URL });
      const email = 'qa+w' + workerInfo.workerIndex + '-' + Date.now() + '@test.com';
      await api.post('/api/test/users', { data: { email, password: 'Secret123' } });

      await use({ email, password: 'Secret123' });

      await api.delete('/api/test/users/' + email);
      await api.dispose();
    },
    { scope: 'worker' },
  ],
});

Mind the restriction: the built-in request and page are test-scoped, so a worker fixture cannot depend on them, otherwise Playwright throws an error. Instead the worker fixture playwright is used: it creates a dedicated API context, closed with dispose(). Uniqueness comes from workerIndex and the time, and cleanup from the guaranteed teardown. After a failed test the worker restarts with a new workerIndex, so a new account is created for it, and the old one is deleted in the teardown.

Auto fixtures. An ordinary fixture is created only on request. The auto: true option starts it for every test (or worker) without being mentioned. This is needed for cross-cutting things: collecting JS errors, checking the console, attaching artifacts. It is convenient but risky: such behavior is invisible in the test. So an auto fixture should contain only what concerns every test, and it should not change business state.

export const test = base.extend<{ pageErrors: string[] }>({
  pageErrors: [
    async ({ page }, use) => {
      const errors: string[] = [];
      page.on('pageerror', (error) => errors.push(error.message));
      await use(errors);
      expect(errors, 'uncaught JS errors on the page').toEqual([]); // in every test
    },
    { auto: true }, // runs without being requested
  ],
});

Option fixtures. This is a parameter with a default value, set in a config project or through test.use. That way the same tests run with a different currency, role or interface language without changing the code. For a typed config, create it through defineConfig<Options>.

// fixtures.ts
export type Options = { currency: string };
export const test = base.extend<Options>({
  currency: ['UAH', { option: true }], // the default value
});

// playwright.config.ts: a different value per project
export default defineConfig<Options>({
  projects: [
    { name: 'uah', use: { currency: 'UAH' } },
    { name: 'eur', use: { currency: 'EUR' } },
  ],
});

// in a file or describe block
test.use({ currency: 'USD' });

Overriding and assembling. Built-in fixtures can be overridden, for example a page already opened on the needed page. When there are many fixtures, they are split into modules (DB, API, UI) and combined with mergeTests, and custom matchers with mergeExpects. A fixture can also get its own timeout: the setup and teardown time counts toward the test timeout, and a slow setup would otherwise eat it.

import { mergeExpects, mergeTests } from '@playwright/test';

// overriding the built-in fixture: page opens the app before the test
const withApp = base.extend({
  page: async ({ page }, use) => {
    await page.goto('/app');
    await use(page);
  },
});

// several modules into one test and one expect
export const test = mergeTests(dbTest, apiTest, withApp);
export const expect = mergeExpects(dbExpect, uiExpect);

// a slow setup gets its own timeout, it does not eat the time of the test
const slow = base.extend<{ seed: void }>({
  seed: [
    async ({}, use) => {
      await seedDatabase();
      await use();
    },
    { timeout: 60_000, auto: true },
  ],
});
KindOptionPurpose
Test fixturedefaultdata and objects for one test
Worker fixture{ scope: 'worker' }expensive setup once per worker
Auto fixture{ auto: true }cross-cutting checks and artifact collection
Option fixture{ option: true }a parameter set in a project or test.use

Limits and alternatives. A worker fixture resolves the conflict between workers, but not between tests of one worker: they share its state and run in turn, so shared data must not be changed without putting it back. If tests need a fully private state, make the fixture test-scoped and move only the expensive part to worker scope. For authentication without logging in again in every test there is a separate mechanism, storageState with a setup project. In Cypress cy.session and cy.task give a similar effect, but there is no paired teardown or injection by name.

Common mistakes.

  • One account for all workers: parallel tests change shared state and fail randomly.
  • A worker fixture that depends on page: a configuration error, because the worker outlives the test.
  • An auto fixture with business logic: the test behaves differently from what its code shows.
  • A copy of the fixture set in every project instead of an option fixture.
  • One giant fixtures.ts file instead of modules and mergeTests.

Check yourself

The worker fixture account creates a user through request from its parameters. What is wrong and how to fix it?

Answer

request is test-scoped, so a worker fixture cannot depend on it. Take the worker fixture playwright and create your own context: playwright.request.newContext(...), not forgetting dispose() in the teardown.

A colleague added an auto fixture that clears the cart before every test. The tests turned green. What is the risk?

Answer

An auto fixture changes business state invisibly: the test behaves differently from what its code shows, and a cart bug that would appear in a real scenario from the previous state gets hidden. Auto is kept for cross-cutting checks and artifact collection, while state preparation is done by an explicit fixture that the test asks for itself.

How to run the same test file with the UAH and EUR currencies without changing the test code?

Answer

Declare an option fixture currency with a default value and set different values in config projects: use: { currency: 'EUR' }. Tests get the needed currency through the parameter, and one file runs in both projects.

In an interview. Junior: A worker fixture is created once per worker, an auto fixture starts for every test without a request, and an option fixture is set in the config. Middle/Senior: For expensive setup I make a worker fixture with workerIndex, so workers do not fight over data, and I remember that it cannot depend on page or request. I keep auto fixtures for cross-cutting checks, option fixtures for parameters between projects, and split a large set into modules assembled with mergeTests.