日本語

Using Playwright Fixtures to Reuse Test Setup

​​Playwright​E2E Testing,TypeScript

If your Playwright E2E tests keep repeating setup, such as opening a page and loading test data or starting an API server, you can group that setup into fixtures and reuse it. A fixture keeps the setup and teardown in one place. A test receives it just by naming it as an argument.

For setup that takes a long time, adding { scope: 'worker' } makes the fixture run once per worker process. In my test environment, with a server whose setup takes 1 second used by 4 tests, creating it for each test took 4.6 to 4.7 seconds in total, and creating it once per worker took 1.6 to 1.7 seconds.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and @playwright/test 1.63.0. The tests were written in TypeScript and ran only on Chromium (headless). Pages were created inline with page.setContent(), and the API server was started inside the test with Node.js's http module on 127.0.0.1. Instead of a slow setup process, I deliberately added a 1-second wait before starting the server. I did not test auto fixtures (auto), option fixtures (values passed from the config), combining fixtures from multiple files with mergeTests, or globalSetup.

Creating a fixture with test.extend

As an example, I use a to-do list page. Every test should start from "a page with two items already in it." I grouped this setup into a fixture called todoPage.

You define a fixture by creating a new test with test.extend(). Calling await use(value) inside the function passes that value to the test. The code before use is setup, and the code after it is teardown.

ts
// tests/fixtures.ts (simplified to only the todoPage part)
import { test as base, expect, type Page } from '@playwright/test';

type TestFixtures = {
  todoPage: Page;
};

export const test = base.extend<TestFixtures>({
  todoPage: async ({ page }, use) => {
    console.log('[todoPage] 準備');
    await page.setContent(todoHtml);
    for (const item of ['牛乳を買う', '本を返す']) {
      await page.getByLabel('新しいやること').fill(item);
      await page.getByRole('button', { name: '追加' }).click();
    }
    await use(page);
    console.log('[todoPage] 後片付け');
  },
});

export { expect };

todoHtml is the HTML of a page that has only an input field, an Add button, and a list. The todoPage function receives the built-in fixture page as an argument. In this way, a fixture can be built on top of another fixture.

In the test file, you import test from this file instead of from @playwright/test, and you name todoPage as an argument. The setup code does not appear in the test.

ts
// tests/todo.spec.ts
import { test, expect } from './fixtures';

test('最初から2件ある', async ({ todoPage }) => {
  console.log('  テスト本体: 最初から2件ある');
  await expect(todoPage.getByRole('listitem')).toHaveCount(2);
});

test('3件目を追加できる', async ({ todoPage }) => {
  console.log('  テスト本体: 3件目を追加できる');
  await todoPage.getByLabel('新しいやること').fill('部屋を片付ける');
  await todoPage.getByRole('button', { name: '追加' }).click();
  await expect(todoPage.getByRole('listitem')).toHaveCount(3);
});

test('フィクスチャを使わないテスト', async ({ page }) => {
  console.log('  テスト本体: フィクスチャを使わないテスト');
  await page.setContent('<p>こんにちは</p>');
  await expect(page.getByText('こんにちは')).toBeVisible();
});

The order in which setup and teardown run

I ran the tests with one worker and checked the order using the console.log output.

text
$ npx playwright test tests/todo.spec.ts --workers=1

Running 3 tests using 1 worker

[todoPage] 準備
  テスト本体: 最初から2件ある
[todoPage] 後片付け
  ✓  1 tests/todo.spec.ts:3:1 › 最初から2件ある (222ms)
[todoPage] 準備
  テスト本体: 3件目を追加できる
[todoPage] 後片付け
  ✓  2 tests/todo.spec.ts:8:1 › 3件目を追加できる (221ms)
  テスト本体: フィクスチャを使わないテスト
  ✓  3 tests/todo.spec.ts:15:1 › フィクスチャを使わないテスト (75ms)

  3 passed (1.2s)

Three things are clear from this.

  • Setup runs for every test. [todoPage] 準備 appears once per test.
  • Teardown runs after the test body finishes.
  • In the third test, which does not take todoPage as an argument, neither setup nor teardown ran.

The third behavior is also described in the official documentation's explanation of execution order. Fixtures other than automatic ones run only when a test needs them. A fixture-based setup runs only in the tests that use it.

Run setup that takes time once per worker

For something like a test API server, which takes time to start and does not need to be recreated for every test, use a worker-scoped fixture. Write it as an array: [function, { scope: 'worker' }]. Declare its type as the second type argument of test.extend.

ts
// tests/fixtures.ts (excerpt)
type WorkerFixtures = {
  apiURL: string;
};

export const test = base.extend<TestFixtures, WorkerFixtures>({
  // (todoPage omitted)

  // Version that starts a server for each test (for comparison)
  apiURLEachTest: async ({}, use) => {
    console.log('[apiURLEachTest] 準備');
    const server = await startServer();
    await use(server.url);
    await server.close();
    console.log('[apiURLEachTest] 後片付け');
  },

  // Fixture that is created only once per worker
  apiURL: [async ({}, use, workerInfo) => {
    console.log(`[apiURL] 準備 worker=${workerInfo.workerIndex}`);
    const server = await startServer();
    await use(server.url);
    await server.close();
    console.log(`[apiURL] 後片付け worker=${workerInfo.workerIndex}`);
  }, { scope: 'worker' }],
});

startServer() waits 1 second, starts a server with http.createServer() that returns the list as JSON, and returns its URL and a function to stop it. I added string for apiURLEachTest to TestFixtures as well. The tests just send a GET request to the received URL with the built-in request.

ts
// tests/api.spec.ts (api-each.spec.ts differs only in using apiURLEachTest and in the test names)
import { test, expect } from './fixtures';

for (const n of [1, 2, 3, 4]) {
  test(`APIから一覧を取れる ${n}`, async ({ apiURL, request }) => {
    console.log(`  テスト本体: APIから一覧を取れる ${n}`);
    const res = await request.get(`${apiURL}/items`);
    expect((await res.json()).items).toHaveLength(2);
  });
}

When I ran with one worker, the worker-scoped fixture ran setup once at the beginning and teardown once at the end.

text
$ npx playwright test tests/api.spec.ts --workers=1

Running 4 tests using 1 worker

[apiURL] 準備 worker=0
  テスト本体: APIから一覧を取れる 1
  ✓  1 tests/api.spec.ts:4:3 › APIから一覧を取れる 1 (35ms)
  テスト本体: APIから一覧を取れる 2
  ✓  2 tests/api.spec.ts:4:3 › APIから一覧を取れる 2 (20ms)
  テスト本体: APIから一覧を取れる 3
  ✓  3 tests/api.spec.ts:4:3 › APIから一覧を取れる 3 (14ms)
  テスト本体: APIから一覧を取れる 4
  ✓  4 tests/api.spec.ts:4:3 › APIから一覧を取れる 4 (18ms)
[apiURL] 後片付け worker=0

  4 passed (1.7s)

With the per-test fixture apiURLEachTest, setup and teardown each ran four times, and each test took 1.0 to 1.1 seconds.

text
$ npx playwright test tests/api-each.spec.ts --workers=1

Running 4 tests using 1 worker

[apiURLEachTest] 準備
  テスト本体: テストごとのサーバー 1
[apiURLEachTest] 後片付け
  ✓  1 tests/api-each.spec.ts:4:3 › テストごとのサーバー 1 (1.0s)
(2〜4件目も同じ順で、どれも 1.0s)

  4 passed (4.6s)

Here are the total times for three runs of each:

Fixture Number of setups Total time (3 runs)
Per test (apiURLEachTest) 4 4.6 s, 4.7 s, 4.6 s
Per worker (apiURL) 1 1.7 s, 1.7 s, 1.6 s
The top row shows four 1-second setups in a row, one for each test. The bottom row shows one 1-second setup, followed by four short test bodies
Number of server setups and total time for four tests

With the worker-scoped fixture, the time of the first test (35 ms) did not include the 1-second setup. With the per-test fixture, each test's time included the 1-second setup. The official documentation's explanation of fixture timeouts also says that setup and teardown time for per-test fixtures counts toward the test timeout, and that worker-scoped fixtures have a separate timeout.

More workers means more setup runs

Because a worker-scoped fixture runs once per worker, two workers mean two setups. I ran two files together with --workers=2 --fully-parallel. [apiURL] 準備 appeared once for worker=0 and once for worker=1, and [apiURLEachTest] 準備 appeared four times. All 8 tests passed in 3.7 seconds. The official documentation describes two ways to run setup only once for the whole test run: globalSetup and project dependencies.

A worker-scoped fixture cannot use page

When I tried to use the built-in page inside a worker-scoped fixture, the run stopped with an error before any test ran. This is because page is a per-test fixture.

ts
// tests/bad/bad.spec.ts (excerpt)
const test = base.extend<{}, { sharedPage: Page }>({
  sharedPage: [async ({ page }, use) => {
    await use(page);
  }, { scope: 'worker' }],
});
text
$ npx playwright test tests/bad --workers=1
worker fixture "sharedPage" cannot depend on a test fixture "page" defined in <builtin>.

   at bad/bad.spec.ts:3
(コードの該当箇所の表示は省略)

As the error message says, page is a per-test fixture. A worker-scoped fixture lives across multiple tests, so it cannot rely on page, which is torn down after each test. Write the setup that opens a page in a per-test fixture, like todoPage.

​Posted by 86