Generics in Playwright: fixtures
The generics of test.extend describe fixture types: the first parameter is for test fixtures, the second for worker fixtures. So a Page Object or API client is typed in every test without !. Options are declared as [value, { option: true }] and their values come from the config. A test must import test from your own file, not from @playwright/test, otherwise the fixture types do not reach it.
TypeScript · Generics
A helper in a test with let api: ApiClient | undefined demands ! everywhere. How do you make api ready and typed in every test?
A typical framework keeps objects such as LoginPage or ApiClient in variables created in beforeEach. Such a variable has the type "an object or undefined", so every test is forced to use !. Playwright fixtures remove the problem: a component is created for a test and its type is known. Generics here are the way to tell Playwright which fixtures were added. The lesson covers how it is arranged and where type errors show up most sharply.
How it works and why. The test.extend method takes generic parameters: the first (TestFixtures) describes test-scoped fixtures, the second (WorkerFixtures) worker-scoped ones. The object passed to extend is checked by the compiler against those types: every fixture has to be implemented, and dependencies in the destructuring ({ page }) are typed from the fixtures that already exist, built-in and added earlier. The use parameter accepts a value of the type declared in the description. After that every test gets typed fixtures from its destructuring. The design is needed because fixture names are string keys: without a type description TypeScript would have no way to know that api is an ApiClient. A fixture is created only when a test asks for it.
Where fixture types come from
Example: from a variable to a fixture. Before:
let api: ApiClient | undefined;
test.beforeEach(({ request }) => {
api = new ApiClient(request);
});
test('user sees balance', async () => {
const acc = await api!.get('/api/accounts/42', AccountSchema);
expect(acc.balance).toBeGreaterThan(0);
});
Here ! removes the check: if the hook did not run, the test fails on undefined and not with a meaningful error. Moreover a module-level variable is shared by the tests of one worker. With fixtures:
import { test as base, expect } from '@playwright/test';
type TestFixtures = { loginPage: LoginPage; api: ApiClient };
type WorkerFixtures = { account: Account };
1export const test = base.extend<TestFixtures, WorkerFixtures>({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
},
2 api: async ({ request }, use) => {
await use(new ApiClient(request));
},
account: [
async ({}, use) => {
const acc = await createAccount();
await use(acc);
await deleteAccount(acc.id);
},
3 { scope: 'worker' },
],
});
4test('user sees balance', async ({ api, account }) => {
const fresh = await api.get('/api/accounts/' + account.id, AccountSchema);
expect(fresh.balance).toBeGreaterThanOrEqual(0);
});
- Descriptions of test and worker fixtures are separate: the two generic parameters of
extend. - Dependencies like
{ request }are typed automatically, anduseaccepts anApiClient. - A worker fixture is given as a pair
[function, { scope: 'worker' }]: the account is created once per worker. - The test gets
apiandaccountwith types and no!.
A test or a worker fixture
extend<TestFixtures>
Created for each test, isolated. For page, clients, Page Objects.
extend<{}, WorkerFixtures>
Created once per worker and shared by its tests. For expensive resources: an account, a database.
The third kind of fixtures is options. A fixture is declared as [value, { option: true }], its value is set in the config, and the config type is passed as a generic to defineConfig. That way, for example, one set of tests runs for different currencies or markets:
// fixtures.ts
export type TestOptions = { currency: 'UAH' | 'USD' };
export const test = base.extend<TestOptions>({
currency: ['UAH', { option: true }],
});
// playwright.config.ts
export default defineConfig<TestOptions>({
projects: [
{ name: 'uah', use: { currency: 'UAH' } },
{ name: 'usd', use: { currency: 'USD' } },
],
});
When fixtures multiply they are split by topic and combined through mergeTests, which also preserves the types:
import { mergeTests } from '@playwright/test';
export const test = mergeTests(dbTest, apiTest);
// a test sees the fixtures of both
Limits and alternatives. Fixture types check only the consistency of the code, not what a fixture really creates. A worker fixture cannot depend on test-scoped fixtures (page, request): it lives longer, and the compiler reflects that. Playwright already has expect.poll for custom expectations, so writing your own generic pollUntil<T> is worth it only when that is not enough. The alternative to fixtures, classes with a constructor and beforeEach, works but brings back the undefined problem.
Common mistakes.
- Describing a worker fixture in the first generic parameter: in the docs they go in the second.
- Keeping a Page Object in a module variable with
!: the type lies and the state is shared by tests. - A worker fixture depending on
pageorrequest: they exist only for the duration of a test. - Importing
testfrom@playwright/testinstead of your own: fixture types will not reach the test.
Check yourself
A test imports test from @playwright/test, while the api fixture is declared in fixtures.ts. What will the compiler show and why?
Answer
An error: the property api does not exist among the fixtures. Types are added only to the test returned by base.extend<...>, so tests must import it from fixtures.ts.
Why does base.extend have two generic parameters instead of one?
Answer
Test and worker fixtures have different lifetimes and different allowed dependencies. Two parameters let the compiler tell them apart: a worker one cannot depend on test ones.
test.extend<Fixtures>(): then a Page Object and an API client have a type in every test with no !. Middle/Senior: The first generic describes test fixtures, the second worker ones, and options are set through { option: true } and defineConfig<Options>. I import test only from my own file, combine sets through mergeTests and keep expensive resources in worker fixtures.