日本語

Playwright Project Dependencies: Run Setup Tests Before Your Tests

​​Playwright​E2E Testing,TypeScript

In a Playwright config, if you add dependencies to a project, the tests in that project start only after all the tests in the listed project have finished. You can write setup and cleanup, such as registering test data through an API before the E2E tests and deleting it afterward, as ordinary tests.

In my test environment, three list-page tests ran after a 2-second setup. With dependencies, the tests started after setup finished at 2.04 seconds. Without it, they started at 0.12 seconds and all three failed. I also checked what happens when setup fails and when tests are narrowed with options such as -g.

Note

The test environment was Ubuntu 24.04, 4 logical CPUs, Node.js 22.23.5, @playwright/test 1.63.0, and TypeScript 5.9.3. I used only Chromium (headless). The page and API came from a small Node.js server that I started through webServer for testing. I did not test Firefox or WebKit, the contents of the HTML report or traces, retries, --shard, or runs on a CI service.

The app and tests used for testing

The server server.mjs keeps a list of cat names in memory. POST /api/cats registers one cat at a time, DELETE /api/cats removes all of them, and opening / returns the list as <li> elements. The server writes received POST and DELETE requests to server.log. Because webServer in the config starts the server again on every run, each run begins with an empty list.

There are three test files. The setup test tests/seed.setup.ts waits 2 seconds in place of a slow real setup, then registers two cats, Tama and Mike, through the API. The log function in the code is a helper I wrote to write timestamps and process IDs (pids) to events.log.

ts
import { test as setup, expect } from '@playwright/test';
import { log } from '../log';

setup('テスト用の猫を登録する', async ({ request }) => {
  log('setup 開始');
  if (process.env.FAIL_SETUP) throw new Error('テスト用データの登録に失敗しました');
  // Wait 2 seconds instead of doing the time-consuming preparation
  await new Promise((r) => setTimeout(r, 2000));
  for (const name of ['たま', 'みけ']) {
    const res = await request.post('/api/cats', { data: { name } });
    expect(res.status()).toBe(201);
  }
  log('setup 終了');
});

FAIL_SETUP is an environment variable for deliberately making setup fail later on. setup is just test under another name, and the body is an ordinary test. The official documentation also says that setup and cleanup code is written as ordinary tests with test(). That means fixtures such as request can be used as they are, and baseURL is taken from the config.

The cleanup test tests/cleanup.teardown.ts only sends DELETE /api/cats.

ts
import { test as teardown, expect } from '@playwright/test';
import { log } from '../log';

teardown('テスト用の猫を消す', async ({ request }) => {
  log('teardown');
  const res = await request.delete('/api/cats');
  expect(res.status()).toBe(204);
});

The main test tests/list.spec.ts opens the list page and checks that the two registered cats appear. FAIL_TEST is there so that I can deliberately make one test fail later.

ts
import { test, expect } from '@playwright/test';
import { log } from '../log';

for (const name of ['たま', 'みけ']) {
  test(`一覧に${name}が出る`, async ({ page }, info) => {
    log(`test ${name} worker=${info.workerIndex}`);
    await page.goto('/');
    await expect(page.getByRole('listitem').filter({ hasText: name })).toBeVisible();
  });
}

test('一覧は2件', async ({ page }, info) => {
  log(`test 2件 worker=${info.workerIndex}`);
  if (process.env.FAIL_TEST) throw new Error('わざと失敗させた');
  await page.goto('/');
  await expect(page.getByRole('listitem')).toHaveCount(2);
});

Set dependencies and teardown in the config

In playwright.config.ts, I list three projects under projects: setup, cleanup, and the main tests. The following is the config I used for testing, with the switching logic I used for comparisons removed.

ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  workers: 4,
  fullyParallel: true,
  reporter: 'list',
  use: { baseURL: 'http://localhost:3100' },
  webServer: { command: 'node server.mjs', url: 'http://localhost:3100', reuseExistingServer: false },
  projects: [
    {
      name: 'setup',
      testMatch: /.*\.setup\.ts/,
      teardown: 'cleanup',
    },
    {
      name: 'cleanup',
      testMatch: /.*\.teardown\.ts/,
    },
    {
      name: 'chromium',
      use: { browserName: 'chromium' },
      dependencies: ['setup'],
    },
  ],
});

Each setting has the following role:

  • testMatch: selects which files a project runs, by file name
  • dependencies: ['setup']: runs the chromium tests after the tests in the setup project have finished
  • teardown: 'cleanup': runs the cleanup project after all the projects that depend on setup have finished

The official explanation of project dependencies says that a project a project depends on runs before the tests of the project that depends on it. As the explanation of teardown says, cleanup runs after all the projects that depend on the setup project have run. The chromium project has no testMatch, so it selects only list.spec.ts, which matches the default file naming rules (such as .spec.ts). Running --list showed that the five tests were distributed across the three projects.

text
$ npx playwright test --list
Listing tests:
  [setup] › seed.setup.ts:4:6 › テスト用の猫を登録する
  [cleanup] › cleanup.teardown.ts:4:9 › テスト用の猫を消す
  [chromium] › list.spec.ts:5:7 › 一覧にたまが出る
  [chromium] › list.spec.ts:5:7 › 一覧にみけが出る
  [chromium] › list.spec.ts:12:5 › 一覧は2件
Total: 5 tests in 3 files

Tests start after setup has finished

Running npx playwright test passed all five tests. In the events.log below, I converted the timestamps to seconds from the first entry and replaced the pids with P0, P1, and so on, in order of appearance.

text
$ npx playwright test
Running 5 tests using 3 workers

  ✓  1 [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する (2.1s)
  ✓  3 [chromium] › tests/list.spec.ts:5:7 › 一覧にみけが出る (214ms)
  ✓  2 [chromium] › tests/list.spec.ts:12:5 › 一覧は2件 (218ms)
  ✓  4 [chromium] › tests/list.spec.ts:5:7 › 一覧にたまが出る (200ms)
  ✓  5 [cleanup] › tests/cleanup.teardown.ts:4:9 › テスト用の猫を消す (27ms)

  5 passed (4.0s)
text
(events.log)
 0.00s P0 setup 開始
 2.04s P0 setup 終了
 2.72s P1 test みけ worker=2
 2.74s P2 test 2件 worker=3
 2.76s P3 test たま worker=1
 3.35s P4 teardown

Setup finished at 2.04 seconds. The three chromium tests then started on three workers at 2.72 to 2.76 seconds. Cleanup ran last, at 3.35 seconds. The server log below shows that the two cats were deleted at the end.

text
POST /api/cats {"name":"たま"} → 1件
POST /api/cats {"name":"みけ"} → 2件
DELETE /api/cats(2件を消した)

Without dependencies, tests start before setup

For comparison, I ran the tests with dependencies emptied from the chromium project only. The setup and cleanup projects were left as they were. The tests started at 0.12 seconds, without waiting for setup to finish, and all three failed. In the output below, I shortened the separator lines and kept only the error message for the first failure. I omitted the call log, the error locations, the other two errors, and the final summary.

text
$ NO_DEPS=1 npx playwright test
Running 5 tests using 4 workers

  ✓  3 [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する (2.0s)
  ✘  1 [chromium] › tests/list.spec.ts:12:5 › 一覧は2件 (5.1s)
  ✘  2 [chromium] › tests/list.spec.ts:5:7 › 一覧にみけが出る (5.1s)
  ✘  4 [chromium] › tests/list.spec.ts:5:7 › 一覧にたまが出る (5.1s)
  ✓  5 [cleanup] › tests/cleanup.teardown.ts:4:9 › テスト用の猫を消す (27ms)

  1) [chromium] › tests/list.spec.ts:5:7 › 一覧にたまが出る ──────────

    Error: expect(locator).toBeVisible() failed

    Locator: getByRole('listitem').filter({ hasText: 'たま' })
    Expected: visible
    Timeout: 5000ms
    Error: element(s) not found
text
(events.log)
 0.00s P0 setup 開始
 0.12s P1 test 2件 worker=3
 0.14s P2 test みけ worker=2
 0.26s P3 test たま worker=1
 2.02s P0 setup 終了
 5.81s P4 teardown

The tests opened the page while the list was still empty. toBeVisible() keeps looking for the element for 5 seconds, but the list on the page stayed empty even after registration finished at 2.02 seconds. The call log for the "list has 2 items" test showed 14 × locator resolved to 0 elements, and it failed with Received: 0.

Two-row diagram. The top row, "with dependencies: ['setup']", shows setup running from 0 to 2.04 seconds, the three tests starting at 2.72 seconds and passing, and cleanup at 3.35 seconds. The bottom row, "without dependencies", shows setup running from 0 to 2.02 seconds. During that time, the three tests start at 0.12 seconds, open the list before registration, and all three fail. Cleanup runs at 5.81 seconds.
Difference in the order that setup and tests run, with and without dependencies

If setup fails, the tests that depend on it do not run

I ran with FAIL_SETUP=1 so that setup threw an error. The three chromium tests did not run, and the output showed 3 did not run. The exit code was 1. In the output below, I shortened the separator lines and omitted the error location.

text
$ FAIL_SETUP=1 npx playwright test
Running 5 tests using 3 workers

  ✘  1 [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する (10ms)
  ✓  2 [cleanup] › tests/cleanup.teardown.ts:4:9 › テスト用の猫を消す (26ms)

  1) [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する ──────────

    Error: テスト用データの登録に失敗しました

  1 failed
    [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する ──────────
  3 did not run
  1 passed (962ms)

The official documentation also says that when a dependency fails, the tests that depend on it do not run. So the main tests do not run after setup has failed, and you do not get a pile of confusing failures.

Warning

Even when setup failed, cleanup, the project set as teardown, still ran. The server log had only one line, DELETE /api/cats, and it removed 0 cats. Write cleanup tests so that they do not error when the data that setup would have created is missing.

Cleanup also runs when a main test fails. I set FAIL_TEST=1 so that only the "list has 2 items" test failed. The other two tests passed, and cleanup ran last and deleted the two cats. In the output below, I kept only the result list and omitted the error details and the summary.

text
$ FAIL_TEST=1 npx playwright test
Running 5 tests using 3 workers

  ✓  1 [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する (2.0s)
  ✘  2 [chromium] › tests/list.spec.ts:12:5 › 一覧は2件 (135ms)
  ✓  4 [chromium] › tests/list.spec.ts:5:7 › 一覧にみけが出る (189ms)
  ✓  3 [chromium] › tests/list.spec.ts:5:7 › 一覧にたまが出る (152ms)
  ✓  5 [cleanup] › tests/cleanup.teardown.ts:4:9 › テスト用の猫を消す (30ms)

Even when tests are narrowed, setup still runs

I also checked what happens when running only one test or file. With -g to select a test by name, the setup and cleanup tests, whose names did not match, still ran, so three tests ran in total.

text
$ npx playwright test -g 一覧は2件
Running 3 tests using 1 worker

  ✓  1 [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する (2.0s)
  ✓  2 [chromium] › tests/list.spec.ts:12:5 › 一覧は2件 (125ms)
  ✓  3 [cleanup] › tests/cleanup.teardown.ts:4:9 › テスト用の猫を消す (31ms)

  3 passed (3.8s)

The result was the same when I passed a file, as in npx playwright test tests/list.spec.ts, and when I selected a project with --project=chromium. In both cases, setup ran first and cleanup ran last, and all five tests passed. According to the official explanation of test filtering, when filtering with --grep or by file, the selected tests are the main tests. If those tests belong to a project with dependencies, all the tests of those dependencies also run.

To skip both setup and cleanup, use --no-deps, which is described on the same page. I checked what happens when setup is skipped with --no-deps, and the errors that result, in the article on saving and reusing login state.

When two projects depend on the same setup

I added a project called small-screen (Chromium with a viewport of 390×844) and gave it dependencies: ['setup'], the same as chromium. All eight tests passed, and setup ran only once.

text
$ TWO=1 npx playwright test
Running 8 tests using 4 workers

  ✓  1 [setup] › tests/seed.setup.ts:4:6 › テスト用の猫を登録する (2.0s)
  ✓  2 [chromium] › tests/list.spec.ts:12:5 › 一覧は2件 (259ms)
  ✓  3 [chromium] › tests/list.spec.ts:5:7 › 一覧にたまが出る (292ms)
  ✓  5 [chromium] › tests/list.spec.ts:5:7 › 一覧にみけが出る (226ms)
  ✓  4 [small-screen] › tests/list.spec.ts:5:7 › 一覧にたまが出る (261ms)
  ✓  6 [small-screen] › tests/list.spec.ts:5:7 › 一覧にみけが出る (195ms)
  ✓  7 [small-screen] › tests/list.spec.ts:12:5 › 一覧は2件 (170ms)
  ✓  8 [cleanup] › tests/cleanup.teardown.ts:4:9 › テスト用の猫を消す (36ms)

  8 passed (4.9s)
text
(events.log)
 0.00s P0 setup 開始
 2.03s P0 setup 終了
 2.67s P1 test 2件 worker=3
 2.70s P2 test たま worker=1
 2.84s P3 test みけ worker=2
 2.89s P4 test たま worker=4
 3.56s P5 test みけ worker=5
 3.59s P6 test 2件 worker=6
 4.28s P7 teardown

The server received two POSTs and one DELETE. cleanup ran at 4.28 seconds, after all six tests in the two projects had finished. Even when you split projects by browser or screen size, data is set up and removed only once each.

Another way to run setup once before the tests is globalSetup in the config. The global setup page recommends project dependencies instead, because the setup results appear in the HTML report, traces can be recorded, and fixtures can be used. I checked how globalSetup behaves in the article on running setup once with globalSetup.

​Posted by 86