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

Playwright › Fixtures and test structure

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.

More articles in this chapter