日本語

Run Playwright test setup once with globalSetup

​​Playwright​E2E tests,TypeScript

If you write globalSetup in the Playwright config file, the function you specify runs once before all tests. You can do setup work, such as starting a test API server before E2E tests or loading data, in a single run regardless of the number of workers.

In my test environment, the setup ran only once even with 4 workers running the tests. The URL of the server it started reached all four tests through an environment variable. I also checked the order of teardown and what happens when the setup fails.

Note

My test environment was Ubuntu 24.04 with 4 logical CPUs, Node.js 22.23.5, and @playwright/test 1.63.0. I wrote the config and tests in TypeScript. The API server the tests used was started inside globalSetup on 127.0.0.1, and it did not connect to any external site. I did not test multiple files listed in globalSetup, trace recording, the HTML report, or running on a CI service.

Adding globalSetup and globalTeardown to the config file

As described in the TestConfig reference, you specify the path to the file with the setup code in globalSetup. Work you want to run once after all tests, such as cleanup, goes in globalTeardown. The playwright.config.ts I used for testing is shown below. I left out the switch lines I used later to compare with beforeAll.

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

export default defineConfig({
  testDir: './tests',
  globalSetup: './global-setup.ts',
  globalTeardown: './global-teardown.ts',
  workers: 4,
  fullyParallel: true,
  reporter: 'list',
  use: { baseURL: 'http://example.com' },
  projects: [{ name: 'chromium', use: { browserName: 'chromium' } }],
});

The setup file global-setup.ts has one function with export default. It receives the whole config (FullConfig) as its argument. In my test, instead of doing slow setup work, it waited 2 seconds and then started an API server on a free port that returns a list of items. The log in the code is a helper function I made to write the time and process ID (pid) to events.log.

ts
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import type { FullConfig } from '@playwright/test';
import { log } from './log';

export default async function globalSetup(config: FullConfig) {
  log('globalSetup 開始');
  if (process.env.FAIL_SETUP) throw new Error('テスト用データの準備に失敗しました');

  // Wait 2 seconds instead of doing slow setup work
  await new Promise((r) => setTimeout(r, 2000));

  // Start exactly one API server for the tests on a free port
  let count = 0;
  const server = http.createServer((req, res) => {
    count++;
    res.setHeader('content-type', 'application/json');
    res.end(JSON.stringify({ items: ['りんご', 'みかん'], count }));
  });
  await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
  const { port } = server.address() as AddressInfo;

  // Put the values to pass to the tests into environment variables
  process.env.API_URL = `http://127.0.0.1:${port}`;
  log(`globalSetup 終了 workers=${config.workers} baseURL=${config.projects[0].use.baseURL}`);

  // The returned function is called once after all tests finish
  return async () => {
    log(`返した関数(後片付け) リクエスト数=${count}`);
    await new Promise((r) => server.close(r));
  };
}

FAIL_SETUP is an environment variable for deliberately making the setup fail later. global-teardown.ts only writes to events.log that it was called.

There are four tests in two files, two in each. Each sends a GET request to process.env.API_URL and checks that the item list is returned. Below is tests/a/items.spec.ts. tests/b/items.spec.ts is the same, with the test names changed to b.

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

for (const n of [1, 2]) {
  test(`a-${n} 商品の一覧を取得する`, async ({ request }, info) => {
    log(`test a-${n} worker=${info.workerIndex} API_URL=${process.env.API_URL}`);
    const res = await request.get(`${process.env.API_URL}/items`);
    const body = await res.json();
    expect(body.items).toEqual(['りんご', 'みかん']);
  });
}

The setup runs only once even with 4 workers

When I ran the tests, all four passed on four workers. The events.log output after that has been converted to seconds from the first record, and each pid has been replaced with P0, P1, and so on in order of appearance. Port numbers are replaced with <port>.

text
$ npx playwright test
Running 4 tests using 4 workers
  ✓  2 [chromium] › tests/a/items.spec.ts:5:3 › a-1 商品の一覧を取得する (22ms)
  ✓  1 [chromium] › tests/b/items.spec.ts:5:3 › b-1 商品の一覧を取得する (34ms)
  ✓  3 [chromium] › tests/a/items.spec.ts:5:3 › a-2 商品の一覧を取得する (25ms)
  ✓  4 [chromium] › tests/b/items.spec.ts:5:3 › b-2 商品の一覧を取得する (26ms)
  4 passed (2.6s)

 0.00s P0 globalSetup 開始
 2.01s P0 globalSetup 終了 workers=4 baseURL=http://example.com
 2.53s P1 test b-1 worker=2 API_URL=http://127.0.0.1:<port>
 2.54s P2 test a-1 worker=0 API_URL=http://127.0.0.1:<port>
 2.58s P3 test a-2 worker=1 API_URL=http://127.0.0.1:<port>
 2.60s P4 test b-2 worker=3 API_URL=http://127.0.0.1:<port>
 2.64s P0 返した関数(後片付け) リクエスト数=4
 2.64s P0 globalTeardown

globalSetup ran once in a separate process (P0) from the workers that run the tests. The four workers (P1 to P4) started after the setup finished at 2.01 seconds. The request count at teardown was 4, which shows that all four tests used the same server.

Two-row diagram. The top row, "When written in globalSetup," shows the setup running once in the parent process from 0 to 2.01 seconds. The tests on workers 0 to 3 run at 2.53 to 2.60 seconds, and the teardown runs at 2.64 seconds. The bottom row, "When written in beforeAll," shows the 2-second setup running once on each of workers 0 to 3 starting at about 0 seconds (0.00 to 0.05 seconds), so it runs four times in total
How the number and timing of setup runs differ depending on where the setup is written

The list reporter output shows only the four test lines and no line for globalSetup. In the record, the time from the start of setup to the end of teardown was 2.64 seconds, which is nearly the same as the total time shown at the end (2.6 s).

I could read the config values from the FullConfig argument. config.workers was 4, and config.projects[0].use.baseURL was the http://example.com set in the config. However, according to the comparison with project dependencies in the official docs, if you use a browser inside globalSetup, you need to launch it yourself with browserType.launch(). Settings such as headless are not applied automatically.

Passing values to tests and the order of cleanup

Values I put into process.env in globalSetup could be read inside the tests. API_URL reached all four tests. The official docs also explain that values such as port numbers and tokens are passed to tests through environment variables. Environment variables are converted to strings, so to pass an object, convert it to a string with JSON.stringify() as in the Playwright docs example, and parse it back with JSON.parse() in the test.

You can write cleanup in two places: the function returned by globalSetup, and the file specified in globalTeardown. When I wrote both, the returned function ran first and then globalTeardown ran (the two lines at 2.64 seconds in the record above). Because the returned function can access the server variable (server) from setup directly, I put the code to close the server there.

The setup also runs when only some tests are run

Even when I selected a single test with -g, globalSetup ran, and the test started after 2 seconds.

text
$ npx playwright test -g a-1
Running 1 test using 1 worker
  ✓  1 [chromium] › tests/a/items.spec.ts:5:3 › a-1 商品の一覧を取得する (43ms)
  1 passed (2.6s)

 0.00s P0 globalSetup 開始
 2.01s P0 globalSetup 終了 workers=4 baseURL=http://example.com
 2.56s P1 test a-1 worker=0 API_URL=http://127.0.0.1:<port>
 2.62s P0 返した関数(後片付け) リクエスト数=1
 2.62s P0 globalTeardown

On the other hand, with --list, which only lists the tests, globalSetup did not run and events.log was not created.

If the setup fails, no tests run

I set FAIL_SETUP=1 and made the setup throw an error. No tests ran, and the exit code was 1. The exit=1 at the end of the output was printed by a test script to show the exit code. I replaced the path of the test environment with /path/to/app.

text
$ env FAIL_SETUP=1 npx playwright test
Error: テスト用データの準備に失敗しました
   at ../global-setup.ts:8
   6 | export default async function globalSetup(config: FullConfig) {
   7 |   log('globalSetup 開始');
>  8 |   if (process.env.FAIL_SETUP) throw new Error('テスト用データの準備に失敗しました');
     |                                     ^
   9 |
  10 |   // Wait 2 seconds instead of a process that takes time to prepare
  11 |   await new Promise((r) => setTimeout(r, 2000));
    at globalSetup (/path/to/app/global-setup.ts:8:37)
exit=1

 0.00s P0 globalSetup 開始
 0.01s P0 globalTeardown
Warning

Even when the setup failed partway through, the file specified in globalTeardown still ran. The returned function did not run, because the failure happened before it was returned. If you do cleanup in globalTeardown, write it so that it does not fail when the things it cleans up were never created.

With beforeAll, the setup runs for each test

For comparison, I put the same 2-second setup in test.beforeAll in the test file tests/hook/hook.spec.ts. The config has a switch that removes globalSetup and globalTeardown only when the environment variable HOOK is set, so that only tests/hook runs. The file has four tests. The config is the same, with workers: 4 and fullyParallel: true.

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

// Same 2-second setup as before, written in beforeAll for comparison
test.beforeAll(async ({}, info) => {
  log(`beforeAll worker=${info.workerIndex}`);
  await new Promise((r) => setTimeout(r, 2000));
});

for (const n of [1, 2, 3, 4]) {
  test(`hook-${n}`, async () => {});
}
text
$ env HOOK=1 npx playwright test
Running 4 tests using 4 workers
  ✓  2 [chromium] › tests/hook/hook.spec.ts:11:3 › hook-3 (8ms)
  ✓  1 [chromium] › tests/hook/hook.spec.ts:11:3 › hook-1 (1ms)
  ✓  3 [chromium] › tests/hook/hook.spec.ts:11:3 › hook-4 (1ms)
  ✓  4 [chromium] › tests/hook/hook.spec.ts:11:3 › hook-2 (1ms)
  4 passed (2.6s)

 0.00s P0 beforeAll worker=2
 0.00s P1 beforeAll worker=0
 0.01s P2 beforeAll worker=3
 0.05s P3 beforeAll worker=1

The total time was the same, 2.6 seconds. However, in this test with four tests on four workers, beforeAll ran four times (in this record, P0 to P3 are all workers). According to the official docs on parallel execution, when tests in a single file also run in parallel, beforeAll runs for each test. For setup that should happen only once, such as starting a single server or loading data once, put it in globalSetup. If one setup per worker is enough, you can also use a worker-scoped fixture.

The official docs recommend a setup project

The global setup page describes, as a way to run setup once before tests, a method that uses project dependencies (dependencies) in addition to globalSetup, and it recommends this method. Because the setup is written as a regular test, its results appear in the HTML report, you can record a trace, and fixtures such as page are available. None of these three things work in globalSetup.

For setup that only starts a server or prepares environment variables without a browser, as in this test, globalSetup is enough. You add one line to the config file and write one function. For setup that uses a browser, such as logging in and saving the browser state, the setup project approach in the official authentication page is a better fit.

​Posted by 86