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

Patterns › Fixtures as Dependency Injection

Fixtures or a base test class

In Playwright, fixtures replace a base class with beforeEach: they are lazy, isolated and have a teardown even after a failure. A base class creates everything for every test, and variables in describe are shared state the compiler does not control. Fixtures are typed and combine through mergeTests; beforeEach stays for a simple local step with no cleanup.

Patterns · Fixtures

A colleague from Java moved BaseTest into Playwright: variables in describe and beforeEach. What is wrong here?

Java Selenium projects have a familiar pattern: a base test class with @BeforeEach where the driver and all pages are created, and tests inherit from it. A candidate carries this scheme over to Playwright: let loginPage variables in describe and filling them in beforeEach. The tests pass, but the benefits of fixtures are gone. This lesson compares both approaches on five criteria and shows where beforeEach is still appropriate.

How it works and why. A base class and hooks run for every test, regardless of whether it needs each object: the base creates everything that may be needed somewhere. Variables in describe are shared state that is overwritten before each test but belongs to the module. Fixtures work differently: a test asks for specific dependencies, the runner creates only those and cleans them up after each test. The difference is not cosmetic, it touches isolation, the cleanup guarantee and types.

A base class or fixtures

Wrong

describe + beforeEach

Everything is created for every test. Variables are shared, and the compiler does not know whether they are filled yet. Cleanup is in a separate hook.

Right

Fixtures

Laziness, isolation, types and cleanup together with creation. Several sets combine through mergeTests.

Figure 1. The same task, another responsibility of the runner.

Example: from beforeEach to fixtures. The starting point. Seemingly tidy until it has to be changed or extended. Four weak places are marked.

test.describe('payments', () => {
1  let loginPage: LoginPage;
  let paymentsPage: PaymentsPage;
  let account: Account;

2  test.beforeEach(async ({ page, request }) => {
    loginPage = new LoginPage(page);
    paymentsPage = new PaymentsPage(page);
    account = await createAccountViaApi(request);
  });

3  test.afterEach(async ({ request }) => {
    await deleteAccountViaApi(request, account.id);
  });

  test('archive is visible', async () => {
    // filled by beforeEach: the compiler does not check it
4    await loginPage.login(account.email, account.password);
  });
});
  1. The variables are declared without values: TypeScript believes they are filled, though that depends on the order of the hooks.
  2. All pages and the account are created, even if the test needs only one of them.
  3. Cleanup lies in a separate hook, far from what it cleans.
  4. The test uses the variables as if they were always ready: an error in the hook shows up elsewhere.

Each of these flaws is small, but together they form a template that gets copied into every describe. Now with fixtures declared earlier in fixtures.ts (as in the lesson on DI):

// fixtures are declared once in fixtures.ts
import { test, expect } from './fixtures';

test.describe('payments', () => {
  test('archive is visible', async ({ loginPage, account }) => {
    await loginPage.login(account.email, account.password);
  });

  test('empty state', async ({ loginPage }) => {
    // account is not requested, so it is not created
    await loginPage.goto();
  });
});

There are no variables and no hooks. The second test does not ask for account, so no account is created or deleted for it: on a large suite this saves API calls and time. Fixtures combine: a set of pages and a set of data live in different files and merge through mergeTests, while a base class can be inherited only once.

Why fixtures are better. First, laziness: only what is needed is created. Second, isolation: each test gets its own instances, not shared fields. Third, teardown together with creation, and it runs even on failure. Fourth, types: the test sees the type of each fixture in its arguments, not a variable that may be uninitialised. Fifth, fixtures can be configured with options (test.use), and that replaces method overriding in descendant classes.

Limits and alternatives. beforeEach remains appropriate for a simple step that concerns one file and needs no cleanup, such as opening the right page:

test.describe('settings', () => {
  // a step for this file only: a fixture would be excessive
  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });
});

The criterion: if the same beforeEach is copied into several files, creates something that must be cleaned up, or passes its result to tests through a variable, it is a candidate for a fixture. Hooks and fixtures can be combined: fixtures prepare objects, and beforeEach performs a local step. For expensive setup shared by a whole file there is beforeAll, but it lives within one worker and gives no test isolation, so a worker fixture is often better for it.

Common mistakes.

  • A describe-level variable filled by beforeEach: the compiler cannot tell "not yet filled" from "ready", and with a changed order or execution mode it easily becomes shared state.
  • One "universal" set in beforeEach for all tests: things the test does not use are created and the set gets slower.
  • Copying the same beforeEach into ten files: the change must be made in all of them, and one is always forgotten.
  • Carrying the BaseTest template from Java without changing the approach: Playwright has its own mechanism for this, and ignoring it means losing cleanup and isolation.

Check yourself

A describe declares let paymentsPage: PaymentsPage filled by beforeEach. Why is this code riskier than a fixture?

Answer

The variable belongs to the module, not to the test. The compiler considers it always filled, though that depends on the order of hooks, and any change of execution mode or a skipped hook leaves the old value from the previous test in it. A fixture is created anew and passed to exactly this test.

When is beforeEach better than a fixture?

Answer

When the step is simple, needed in one file only and creates no resources that must be cleaned up, for example opening the settings page. If the same hook is copied, returns a value into a variable or requires cleanup, it should move into a fixture.

In an interview. Junior: In Playwright I do not make a BaseTest, because fixtures give lazy creation, isolation and guaranteed cleanup. I keep beforeEach for simple steps within one file. Middle/Senior: A base class creates everything for all tests, and describe variables are shared state the compiler does not control. Fixtures are requested by the test, combine through extend and mergeTests, have types and a teardown after use that runs on failure too. A hook stays where the step is local and needs no cleanup; if it gets copied, it becomes a fixture.

More articles in this chapter