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

Playwright

Config, projects, parallelism, CI

Configuration and projects

A config has three levels: run behaviour at the top level, context options in use, and run variants in projects. A project is not a folder of tests but a way to run them: a test matched by three projects produces three runs, each with its own use. Command-line flags override the config, and --list shows what will run. CI enables forbidOnly, and flaky in a report means debt.

Playwright · Config and CI

Green locally, red on CI. Is it the test that differs, or the config?

A test is green on a laptop and red on CI. The code is the same but the run is different: locally one project starts, on CI all three browsers; locally there are no retries, on CI there are two, and a test that fails every other run stays unnoticed in a green pipeline. None of this is decided by the test, it is decided by playwright.config.ts. This lesson shows how to split settings into levels, what projects are, and how to check what is going to run.

How it works and why. The config is an ordinary TypeScript module that exports defineConfig(...); the runner reads it once before the run. Settings are split into three levels because they answer three different questions:

LevelQuestionExamples
Top levelHow the run behavestestDir, timeout, retries, workers, fullyParallel, forbidOnly, reporter, webServer
useWhat the browser context and fixtures are likebaseURL, trace, screenshot, viewport, locale, storageState
projects[]Which run variants existname, use, testMatch, grep, dependencies, teardown

A project is not a folder of tests but a run variant. The runner finds all the tests, then for each project runs those that pass its filters (testMatch, grep), with its use. So one test in three projects gives three separate runs, and each one carries the project name in the report. A project's use is layered over the top-level one: whatever the project does not set stays from the shared part. A project can have its own retries, timeout, testDir and fullyParallel.

One file, several runs

checkout.spec.ts2 tests, one tagged @mobile chromium2 runs firefox2 runs mobile1 (grep @mobile) The report shows 5 runs named by project
Figure 1. A project multiplies tests: the number of runs is the sum over projects, not the number of tests in the file.

Example: the pipeline is green, but a test is unstable. The initial config looks harmless:

// before
export default defineConfig({
  retries: 3,
  use: { baseURL: 'http://localhost:3000' },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
  ],
});

There are three problems. Retries are the same everywhere: a test that fails every other run is just "re-run" locally and never draws attention. A forgotten test.only will reach the pipeline and quietly shrink the run to one test. And baseURL is hard-coded, so the same suite cannot be run against stage. The fixed version:

// after
export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,       // test.only on CI = an error
  retries: process.env.CI ? 2 : 0,    // locally a failure is visible at once
  reporter: process.env.CI ? [['blob'], ['github']] : [['html', { open: 'never' }]],
  use: {
    baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
    trace: 'on-first-retry',          // a trace only when there was a second attempt
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'mobile', use: { ...devices['Pixel 7'] }, grep: /@mobile/ },
  ],
});

A test that passed on the second attempt has the status flaky in the report, not passed, and trace: 'on-first-retry' keeps a trace for it. That is why retries on CI are acceptable: they do not hide the problem as long as someone looks at the report. You can check what will run without running the tests:

npx playwright test --list
Listing tests:
  [chromium] › checkout.spec.ts:4:5 › pay by card
  [firefox] › checkout.spec.ts:4:5 › pay by card
  [chromium] › checkout.spec.ts:12:5 › mobile menu
  [firefox] › checkout.spec.ts:12:5 › mobile menu
  [mobile] › checkout.spec.ts:12:5 › mobile menu
Total: 5 tests in 1 file

Each line shows the project in square brackets, so it is clear at once what will go to CI. A single project is run with --project=chromium; the flag can be repeated.

Skipping a test: how it looks in the report

Typical

if inside the body

The test does a return on the mobile project. In the report it is "passed" without a single check, and nobody knows that nothing was executed.

Better

test.skip with a condition

test.skip(isMobile, 'reason'): the report shows "skipped" and the reason text, so it is visible what was not verified.

Figure 2. A conditional skip must stay visible, otherwise the report lies about coverage.
test('drag and drop cards', async ({ page, browserName, isMobile }) => {
  test.skip(isMobile, 'Drag and drop is not supported in the mobile version');
  test.fixme(browserName === 'webkit', 'Known WebKit bug, see the ticket');
  // …
});

Limits and alternatives. Command-line flags take priority over the config: --retries, --workers, --project, --grep and --reporter override the values from the file, so on CI they can be changed without editing code. If there are several configs (a regular one and one for a nightly run), the shared part goes into a base object: defineConfig(base, { … }) merges them. Without an explicit reporter Playwright uses dot on CI and list locally, so without your own reporter CI has no HTML report. Cypress has a similar role in the e2e block of cypress.config.ts and the --browser flag, but there are no "projects" as separate run variants. Selenium has no runner with a config: you assemble the browser matrix yourself, through TestNG, pytest or CI.

Common mistakes.

  • Putting baseURL or storageState at the top level: these are context options, they belong in use. TypeScript will flag the extra key, while in a JS config it is simply ignored, and page.goto('/') fails because the relative path has no base.
  • Making a project for every small thing: copies of nearly identical projects drift apart. The shared part goes into an object extended through ....
  • A mobile project without grep or testMatch: the whole suite also runs in the mobile profile, the run takes twice as long, and half of the failures are noise.
  • High retries locally: unstable tests become invisible and are discovered when there are already many.
  • No forbidOnly on CI: one forgotten test.only removes all other tests from the run.

Check yourself

The config has chromium, firefox and mobile (with grep: /@mobile/). A file has two tests, one tagged @mobile. How many runs will the report show?

Answer

Five: 2 in chromium, 2 in firefox and 1 in mobile. Projects without grep take all tests, while mobile takes only those that pass the filter.

A test passed on CI on the second attempt, the pipeline is green. Does that mean everything is fine?

Answer

No. The report status will be flaky: the test is unstable, the retry only kept it from stopping the run. Open the trace (with on-first-retry it is recorded on the retry; a trace of the failure itself needs retain-on-first-failure) and find the cause, instead of treating a green pipeline as proof of stability.

baseURL is written at the top level of the config, and page.goto('/login') does not work. What is wrong?

Answer

baseURL is a context option, so it lives in use. There is no such key at the top level: TypeScript shows this, while a JS config silently ignores the key and the relative path is left without a base.

In an interview. Junior: The config has run settings, options in use and projects: each project, for example a browser, runs the tests with its own options. Middle/Senior: I treat a project as a run variant: a test in three projects gives three runs in the report. On CI I turn on forbidOnly, retries and trace: 'on-first-retry', but I remember that flaky in the report means debt, not success. I make conditional skips through test.skip with a reason so they stay visible, and before a pipeline I check the make-up of the run with --list.

Parallelism, workers and sharding

Tests run in workers, separate Node processes: files in parallel by default, individual tests with fullyParallel. After a failure the worker is closed and a new one starts, but that resets the browser, not the server state, so tests need their own data, such as a user created in a fixture. Sharding splits a run across machines, and shard reports are merged with the blob reporter and merge-reports.

Playwright · Config and CI

Tests are green with one worker and fail with eight. Who is stealing whose data?

On a laptop the tests run in four workers and pass. On CI an unstable failure appears: "wrong password" in a test that worked yesterday. The cause is not the browser: two tests logged in with the same account, and one of them was changing the password. Parallelism does not break tests, it reveals which of them share data. This lesson explains how Playwright distributes tests across workers, what happens after a failure, and how to make tests independent.

How it works and why. A worker is a separate Node process with its own browser. The default count is half of the logical cores; it is set through workers (a number or a percentage such as '50%') or the --workers flag. Workers share no memory, so tests in different workers share neither variables nor pages. The default unit of work is a file: different files run in parallel, while the tests of one file run one after another in a single worker. With fullyParallel: true the unit becomes a single test.

What counts as a unit of work

By default

Files run in parallel, the tests of a file one after another. One big file occupies one worker while the rest sit idle.

fullyParallel: true

Single tests run in parallel, even from one file. The load is more even, but tests must be independent.

Figure 1. The mode decides what the runner hands out to workers: files or tests.

A separate safety rule applies: when a test fails, the worker is shut down and the following tests start in a new one. That way browser state, cookies and open connections do not leak from a broken test into the next one.

What happens to a worker after a failure

Worker 1 test 1 test 2 Worker 2 test 3 test 4 Test 2 failed: worker 1 is shut down. Tests 3 and 4 run in a new worker with a fresh browser.
Figure 2. After a failure the test does not spoil the next ones: a new process runs them. Shared data outside the browser (an account, a DB record) is not cleaned this way.

The last sentence of the caption matters: a fresh process heals browser state but not server state. If tests share an account or a database record, isolation ends where the network begins.

Example: a shared account. A typical cause of an "unstable" failure:

// before: one account for all tests
const USER = { email: 'qa@test.app', password: 'Secret-1' };

test('change password', async ({ page }) => {
  await login(page, USER);
  await changePassword(page, 'New-2');   // until the password is restored, logging in with the old one fails
  await changePassword(page, USER.password);
});

test('profile opens', async ({ page }) => {
  await login(page, USER);               // sometimes: "Wrong password"
  await expect(page.getByRole('heading', { name: 'Profile' })).toBeVisible();
});

With --workers=1 the tests run one after another, and the order happens to save them. To prove the cause is parallelism and not a locator, compare two runs: npx playwright test --workers=1 (green) and npx playwright test --workers=4 --repeat-each=5 (red). The cure: each test gets its own user. A fixture creates it through the API and removes it after the test, even if the test failed:

The account fixture: what each line does

import { test as base } from '@playwright/test';
import { randomUUID } from 'node:crypto';

export const test = base.extend<{
  account: {
    email: string;
    password: string;
  };
}>({
  account: async (
    { request },
    use,
  ) => {
1    const email =
      'qa-' +
      randomUUID() +
      '@test.app';
    const password =
      'Secret-' + randomUUID();
2    const res = await request.post(
      '/api/users',
      {
        data: { email, password },
      },
    );
    const { id } =
      await res.json();
3    await use({ email, password });
4    await request.delete(
      '/api/users/' + id,
    );
  },
});
  1. Unique data: The email and password are unique per test, so workers do not share an account.
  2. Create: The account is created through the API, without a sign-up form.
  3. use: The test receives a ready account.
  4. Cleanup: The account is deleted after the test.
Figure 3. The numbers lead to the explanations of the code lines.

A UUID is more reliable for unique values. Worker indexes exist too: testInfo.parallelIndex is a stable slot from 0 to workers - 1 (useful when, say, one prepared account falls to each worker), while testInfo.workerIndex changes when a worker is restarted after a failure.

Describe modes. test.describe.configure({ mode: 'serial' }) runs a block's tests one after another in one worker: if one fails, the rest are skipped, and on a retry the block starts from the first test. The 'parallel' mode, on the contrary, parallelises tests in one file even when fullyParallel is off. Keep serial for steps that really do not exist on their own, and even then carefully: a variable between tests (let orderId) works only because both tests are in one worker, and running only the second test with -g will not reproduce the failure.

Sharding. This is one more level of parallelism: the run is split between machines with npx playwright test --shard=1/4. Without fullyParallel the split goes by files, so uneven files give a skew between shards; with it, tests are distributed individually. Shard reports are combined with the blob reporter and merge-reports; the full pipeline is covered in the CI lesson.

Limits and alternatives. Data isolation is not free: creating a user through the API adds a request per test. A cheaper scheme is one account per worker through a worker fixture (it lives as long as the worker does), but then tests of one worker share the account again and must not change its state. If a resource cannot be multiplied (a single global flag, a licence slot), those tests go to a separate --workers=1 run selected by a tag. In Cypress, parallelism means separate machines and a paid or self-hosted orchestrator, while inside one spec the tests always run one after another; in Selenium parallelism comes from TestNG, JUnit or pytest-xdist, and data isolation is also yours to solve.

Common mistakes.

  • A shared account or DB record: with --workers=1 the tests are green, in parallel they fail every other run, and the stack trace explains nothing.
  • Depending on the order of tests in a file without serial: it breaks with --shard, -g or fullyParallel.
  • Too many workers on a weak runner: browsers compete for CPU, timeouts fire, and the failure looks like an application bug.
  • Cleaning data at the end of a test instead of in a fixture after use: on a failure it does not run and litters the database.
  • A module-level variable as shared state between tests: each worker has its own process and its own copy of the variable.

Check yourself

Two tests in one file, fullyParallel is not enabled, four workers. One changes a password, the other logs in with the same account. Can they conflict?

Answer

No, while fullyParallel is off: tests of one file run one after another in one worker. But turn on fullyParallel, add sharding, or run these files with other tests of the account, and the conflict appears. The order dependency is hidden, and it should be removed with a separate account.

Test 2 failed, and then test 3 failed too, but only on CI. Why do new workers not guarantee a clean start?

Answer

A new worker gives a fresh browser and process but does not clean the server. If test 2 left a DB record or changed an account, test 3 will see that state. So data is created in a fixture and removed after use.

What will a run with --workers=1 and one with --workers=4 --repeat-each=5 show for a test with shared data?

Answer

The first is most likely green, because the execution order is deterministic. The second raises the chance of workers colliding and reproduces the unstable failure. If the behaviour differs, the cause is shared state, not a locator or a wait.

In an interview. Junior: Playwright runs files in parallel in workers, and with fullyParallel tests in a file too, so each test must work with its own data. Middle/Senior: A worker is a separate process; after a failed test it is shut down, but that does not clean server state, so I create unique users in a fixture through the API and delete them after use. I prove instability from shared data by comparing --workers=1 with --workers=4 --repeat-each. I take serial rarely, and for sharding I turn on fullyParallel and merge blob reports.

Timeouts and the priority of settings

Playwright has nested timeouts, and the first line of the error says which one fired. By default a test has 30 s, an expect assertion 5 s, and actions and navigation have no separate limit until one is set. The most specific setting wins: a call option overrides the config. A slow step is marked precisely instead of raising a global limit, and globalTimeout and maxFailures protect CI from hangs.

Playwright · Config and CI

A test failed with “Timeout exceeded”. Which limit fired, and where do you change it?

On CI a test fails, and the first line in the log is Test timeout of 30000ms exceeded. The usual reflex is to raise timeout to two minutes. The test turns green, the run gets longer, and the real cause (a button nobody can see, or a slow endpoint) has not gone anywhere. Playwright has several timeouts, each one covers its own slice of time, and the first line of the error says which one fired. This lesson teaches how to read that and tune it precisely.

How it works and why. The limits are nested. The outer one bounds the whole run, the next one each test, and inside a test actions, navigations and assertions have counters of their own. The nesting exists for diagnostics: when an inner one fires, the error names the concrete action and shows a wait log, and when only the outer one fires, you see just "did not fit".

TimeoutDefaultWhere to set
Test (together with beforeEach and fixture setup; afterEach and fixture teardown get a separate limit of the same length)30 stimeout, test.setTimeout
The expect assertion5 sexpect.timeout
Action (click, fill)0, no separate limituse.actionTimeout
Navigation (goto)0, no separate limituse.navigationTimeout
The whole run0, no limitglobalTimeout

The limits are nested

globalTimeout: whole run, unlimited by default test timeout: 30 stest + beforeEach + fixture setup action (click, fill)use.actionTimeout navigation (goto)navigationTimeout expect assertionexpect.timeout: 5 s beforeEachinside the test limit nested limits live within the test timeout
Figure 1. An action or an assertion has its own counter, but none can outlive the test timeout.

Example: what the first line says. A test generates a report and waits for a button. Without actionTimeout the action waits until the whole test is used up, and the error looks like this (shortened):

Error: locator.click: Test timeout of 30000ms exceeded.
Call log:
  - waiting for getByRole('button', { name: 'Generate' })

The first line says time ran out in the test, not in the action, so one stuck action ate all 30 seconds. The log shows it was waiting for the locator. The same case with actionTimeout: 10_000 looks different:

Error: locator.click: Timeout 10000ms exceeded.

The failure arrives twenty seconds earlier, and the text names the action. For an assertion the form is different (shortened):

Error: expect(locator).toBeVisible() failed

Locator: getByText('Report is ready')
Expected: visible
Timeout: 5000ms
Error: element(s) not found

Hence the diagnostic table: Test timeout of … means the whole test did not fit (look at which action is in the next line); locator.click: Timeout … means the action limit fired; expect(…) failed with a Timeout: 5000ms line means the assertion never got its condition. Settings in the config:

Timeouts in the config: what each line limits

export default defineConfig({
1  timeout: 45_000,
2  expect: { timeout: 7_000 },
3  globalTimeout: 30 * 60_000,
  maxFailures: process.env.CI
    ? 10
    : 0,
  use: {
4    actionTimeout: 12_000,
    navigationTimeout: 30_000,
  },
});
  1. timeout: The limit of one test. 30 seconds by default.
  2. expect: How long a web-first assertion waits for its condition. 5 seconds by default.
  3. globalTimeout: The limit of the whole run: the runner stops instead of working for hours.
  4. actionTimeout: The limit of one action (click, fill): a stuck action fails fast instead of eating the whole test.
Figure 2. The numbers lead to the explanations of the code lines.

And a slow but legitimate step is marked selectively, instead of raising the limit for everyone:

test('generating a large report', async ({ page }) => {
  test.slow();                        // this test's timeout is three times larger
  await page.goto('/reports');
  await page.getByRole('button', { name: 'Generate' }).click();
  // only this assertion waits longer, the others keep the 7 s from the config
  await expect(page.getByText('Report is ready')).toBeVisible({ timeout: 30_000 });
});

test.describe('slow integrations', () => {
  test.describe.configure({ timeout: 90_000 });
  // …
});

There is also test.setTimeout(60_000) for one test and test.slow(condition, reason) for conditional cases (say, a slow browser). A long fixture setup can have its own timeout in the fixture options: then it does not eat the test's limit. Each retry gets the test timeout afresh.

Priority of settings. The same setting can be given in several places, and the most specific one wins.

Who overrides whom

1 config top leveluse: { actionTimeout } 2 use of a specific projectprojects[].use 3 file or describetest.use, describe.configure 4 an action or assertion callclick({timeout}), expect(…,{timeout})
Figure 3. General on top, specific below: a lower level overrides a higher one. CLI flags such as --timeout and --retries override the values from the config file.

test.use cannot be called in a test body, only at file or describe level: context options are needed before the context is created. test.setTimeout and test.slow affect one test and work inside it.

Limits and alternatives. A longer timeout cures only slow but real waiting. A button covered by a banner will wait 60 seconds just as well. Protection from hangs on CI comes from globalTimeout (the run stops instead of eating hours of the runner) and maxFailures (after N failures, when the environment is obviously down). In toPass the default timeout is 0, so it is set explicitly. Cypress has defaultCommandTimeout (4 s per command) and pageLoadTimeout for this; in Selenium implicit and explicit waits are configured separately, and mixing them is discouraged.

Common mistakes.

  • Raising the global timeout to 5 minutes to make things "pass": a slow endpoint or an extra navigation gets hidden, and every real hang now costs 5 minutes.
  • Adding waitForTimeout instead of waiting for a condition: no flexibility and no diagnostics, and in a fast environment it is just a pause.
  • Confusing an assertion timeout with a test timeout: an assertion waits 5 seconds even if the test has 25 left.
  • Not setting actionTimeout: a stuck action burns the whole test, and the error does not point at it at once.
  • Putting test.slow() on every test of a file "just in case": tests that really hang are allowed to hang three times longer.

Check yourself

The log says: Error: locator.click: Test timeout of 30000ms exceeded. What does that say about the cause and what do you do first?

Answer

The test timeout fired, not the action's: the click got stuck and ate all 30 seconds. Read the wait log below (is the element found, is it covered) and fix the cause. It helps to set actionTimeout, so that such an action fails earlier and is named at once.

A test has 25 seconds in reserve, yet toBeVisible() fails after 5. Is that a config malfunction?

Answer

No, that is normal: an assertion has its own expect.timeout of 5 seconds, regardless of what is left of the test. If the wait is legitimately long, increase it with the option of that particular assertion.

The config has actionTimeout: 10_000, and one call has click({ timeout: 30_000 }). How long will this click wait?

Answer

Up to 30 seconds, but no longer than what is left of the test timeout. The call option overrides the config, while the test is still the outer boundary.

In an interview. Junior: A test has 30 seconds by default, an assertion 5, and actions and navigation have no separate limit. Middle/Senior: I read the first line of the error to know which limit fired, set actionTimeout so that a concrete action fails, and mark slow steps selectively with test.slow() or an assertion option instead of raising the global timeout. On CI I add globalTimeout and maxFailures so as not to burn resources when the environment is down.

webServer and environment variables

The webServer option starts the application before the tests, polls the url and starts the tests only once the server has answered. A server counts as ready with a 2xx, 3xx or 400-403 status, so polling needs an address such as /health. Locally reuseExistingServer lets Playwright reuse a running server, while in CI a fresh process starts. The environment is chosen with a variable from which the config takes baseURL.

Playwright · Config and CI

The test starts before the app and fails with ERR_CONNECTION_REFUSED. How do you get rid of that?

Locally the app is already running in a neighbouring terminal, and the tests pass. On CI nobody started it: the very first page.goto fails with net::ERR_CONNECTION_REFUSED. The recipe "the README says to start the server first" does not scale. The webServer option makes starting the app part of the run, while baseURL and environment variables let the same suite run against different environments without code changes.

How it works and why. Before the first test Playwright starts the given command as a child process, polls url until the server answers, and only then starts the tests. A server counts as ready when it answers with status 2xx, 3xx or 400-403: a page that returns 404 never becomes "ready", so polling needs an address that returns success (often a separate /health). After the run Playwright stops the process itself. Why so much care about readiness: a port opens earlier than the app can serve requests, and tests that start on the port fail on their first requests.

The life of webServer in a run

1 start command 2 poll url not ready:wait, again 2xx, 3xx, 400-403 3 tests start 4 process stopped timeout error:no tests run
Figure 1. Tests start only after a successful answer from url. If that does not happen within timeout (60 s by default), the run ends with an error.

Example: from the failure to a working config. Before: a test with a hard-coded full address and a manual start.

// before
test('login', async ({ page }) => {
  await page.goto('http://localhost:3000/login');
  // …
});

Reading the error: the app is not running

1Error: page.goto: net::ERR_CONNECTION_REFUSED at 2http://localhost:3000/login
Call log:
3  - navigating to "http://localhost:3000/login", waiting until "load"
  1. What: the browser could not connect: nothing listens at that address. It is not a test error, it is a missing server.
  2. Where to: port 3000 on the local machine: the app is not started (or listens on another port or host).
  3. Where: this is the very first navigation, so the test had no chance to check anything.

What to do

Describe the app start in webServer (command and url) and use relative paths with baseURL. Then the run starts the app itself and waits until it answers.

Figure 2. The real error text (shortened): the numbers lead to the explanations.

After: the config brings the app up, and the test uses a relative path.

// playwright.config.ts
export default defineConfig({
  webServer: [
    {
      command: 'npm run start:api',
      url: 'http://localhost:4000/health',
      reuseExistingServer: !process.env.CI,
      timeout: 120_000,
    },
    {
      command: 'npm run start:web',
      url: 'http://localhost:3000',
      reuseExistingServer: !process.env.CI,
      stdout: 'pipe',   // show the server output when it fails to start
    },
  ],
  use: { baseURL: process.env.BASE_URL ?? 'http://localhost:3000' },
});

// in the test
await page.goto('/login');

reuseExistingServer: !process.env.CI gives two modes. Locally, if a server is already running, Playwright uses it instead of trying to take the same port. On CI it always starts a fresh process and fails with a message if the port is taken, so there is no accidental "foreign" server. An array is needed when a backend and a front end both have to come up. By default the server's stdout is hidden and stderr is shown; stdout: 'pipe' turns the output on, and the reason a server does not start is visible in the log. For a heavy front end it is better to build in advance and start the ready build (build + start) than a dev server: it starts faster and behaves like production.

Environments. For several environments you keep .env.dev and .env.stage files and choose one with a variable, for example TEST_ENV. A separate module that checks required variables gives a clear error instead of undefined in the middle of a test:

// env.ts
import dotenv from 'dotenv';

export const TEST_ENV = process.env.TEST_ENV ?? 'dev';
dotenv.config({ path: '.env.' + TEST_ENV });   // does not overwrite variables already set

export function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error('Missing ' + name + ' for TEST_ENV=' + TEST_ENV);
  return value;
}
// playwright.config.ts
import { defineConfig } from '@playwright/test';
import { requireEnv } from './env';

export default defineConfig({
  use: { baseURL: requireEnv('BASE_URL') },
});

Who wins when a variable is set twice

Better

A variable from CI or the terminal

It is already in process.env, so dotenv does not touch it. It always wins, and this is where secrets live.

The .env.stage file

It fills in only what is missing. The repository holds non-secret values, and locally you can have your own .env listed in .gitignore.

Figure 3. By default dotenv overwrites nothing, so a pipeline value is always stronger than the file.

As long as baseURL comes from a variable and test code uses relative paths, the same suite works on any environment by changing one variable. A full URL in a test ties it to one environment.

Limits and alternatives. Several environments can be described by projects with different baseURL values and filters:

projects: [
  { name: 'stage', use: { baseURL: 'https://stage.app.test' } },
  { name: 'prod-readonly', use: { baseURL: 'https://app.test' }, grep: /@readonly/ },
],

On prod the tests only read and create no records: it is a real environment. webServer is needed when the app comes up together with the tests. If an environment is already deployed (stage), it is not turned on, you only set baseURL. A complex stack with a database and several services is more often brought up by a separate pipeline step (docker compose), and readiness is awaited there. In Cypress a separate package such as start-server-and-test is usually used for this, while Playwright has it built in.

Common mistakes.

  • Forgetting reuseExistingServer locally: the run does not start because your dev server took the port, while Playwright demands a fresh one.
  • Turning reuseExistingServer on in CI: tests connect to a foreign or stale process and verify the wrong code.
  • Polling in url a page that responds earlier than the API is ready: tests start and fail on the first requests. A separate /health exists for this, which answers only when everything is up.
  • Keeping secrets in .env.stage in the repository: environment files hold only non-secret values, and passwords come from CI.
  • A timeout that is too short for a cold start: a build on CI takes longer than on a laptop.

Check yourself

The server starts and the port is open, but webServer keeps waiting and finally fails on timeout. url points to /, which returns 404. What is going on?

Answer

A server counts as ready with a status of 2xx, 3xx or 400-403, and 404 is not among them. Playwright decides the server is not ready yet and waits until the timeout. Point to an address that returns success, for example /health.

On CI the variable BASE_URL is set to stage, while .env.dev says localhost. Which value will the test get?

Answer

Stage. dotenv does not overwrite variables that are already in process.env, so the CI value is stronger than the file.

Why is reuseExistingServer: false better on CI?

Answer

So that the tests surely run against freshly started code from the current commit. With true the run could pick up a foreign or stale process on the same port and give a false result.

In an interview. Junior: The webServer option starts the app before the tests and waits until it answers, and baseURL lets tests use relative paths. Middle/Senior: I give url an endpoint that returns 2xx only when the app is ready, set reuseExistingServer: !process.env.CI, and for a heavy front end run a ready build. I choose the environment with a variable from which the config takes baseURL; secrets come from CI, and dotenv does not overwrite them.

CI: sharding, Docker and fast reruns

A run is split across machines with the --shard=x/y flag, and the shards' blob reports are merged into one HTML report with merge-reports. The shard matrix uses fail-fast: false, unique artifact names and a report-merging job under the !cancelled() condition. The official Docker image of the same version as @playwright/test evens out fonts and libraries. --only-changed gives quick feedback in a PR, but the full run before merge stays.

Playwright · Config and CI

A run takes 40 minutes on one machine. How do you split it without losing the report?

The suite grows, and a single CI machine already holds the tests for forty minutes. Adding workers does not help: the runner has two cores. There are two requirements: make the run faster and keep one clear report instead of four scattered ones. Sharding splits tests between machines, the blob reporter lets you assemble the report back, and the official Docker image evens out the environment. This lesson breaks the pipeline into parts and shows what breaks in it most often.

How it works and why. The --shard=x/y flag splits the list of tests into y parts, and each machine runs its own, the x-th. The machines do not talk to each other: each takes its part of the list by the same deterministic rule, so shards do not overlap. Each shard sees only part of the tests, so its HTML report is incomplete. That is what the blob reporter is for: a shard stores its result in an intermediate form, and a separate job collects all the blobs and builds a single report. Without fullyParallel the split goes by files, so uneven files cause a skew; with it, shards take individual tests and balance more evenly.

Shards, blobs and one merge job

shard 1/4blob shard 2/4blob shard 3/4blob shard 4/4blob merge-reportsone job after all the shards a single HTML report
Figure 1. Shards work independently, and the report is assembled once at the end.

Example: from one job to a matrix. Before: a single npx playwright test step taking 40 minutes. After: a matrix of four shards in the official image.

jobs:
  e2e:
    strategy:
      fail-fast: false
      matrix:
        shardIndex: [1, 2, 3, 4]
        shardTotal: [4]
    runs-on: ubuntu-latest
    # image version = the @playwright/test version from package.json
    container:
      image: mcr.microsoft.com/playwright:v1.65.0-noble
      options: --user 1001
    steps:
      - uses: actions/checkout@v6
      - run: npm ci
      - run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
        env:
          CI: true
      - uses: actions/upload-artifact@v5
        if: ${{ !cancelled() }}
        with:
          name: blob-report-${{ matrix.shardIndex }}
          path: blob-report
          retention-days: 1

The blob reporter is turned on in the config through process.env.CI, not with a flag in every step. A separate job collects the artifacts:

  merge-reports:
    if: ${{ !cancelled() }}
    needs: [e2e]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - run: npm ci
      - uses: actions/download-artifact@v5
        with:
          path: all-blob-reports
          pattern: blob-report-*
          merge-multiple: true
      - run: npx playwright merge-reports --reporter html ./all-blob-reports
      - uses: actions/upload-artifact@v5
        with:
          name: html-report
          path: playwright-report

The CI config: what each line does

export default defineConfig({
1  fullyParallel: true,
  forbidOnly: !!process.env.CI,
2  retries: process.env.CI ? 2 : 0,
3  workers: process.env.CI
    ? '50%'
    : undefined,
4  reporter: process.env.CI
    ? 'blob'
    : 'html',
  use: { trace: 'on-first-retry' },
});
  1. fullyParallel: Tests of one file also run in parallel, so shards split the work evenly.
  2. retries: Two retries in CI, none locally.
  3. workers: Half of the logical cores, the same as the default: the line only makes it explicit. On a two-core runner that is one worker.
  4. reporter: In CI each shard writes a blob report, and the blobs are merged into one HTML report later.
Figure 2. The numbers lead to the explanations of the code lines.

A few details people trip on. fail-fast: false is needed so that one failed shard does not cancel the rest: otherwise the report is incomplete. !cancelled() (and not success()) in the artifact step and in the merge job gives a report exactly when tests have failed. The image version must match @playwright/test, otherwise the needed browser is not found. The image provides identical fonts and system libraries, which matters for screenshot tests. Without Docker, browsers are installed with npx playwright install --with-deps.

The artifact name of a shard

Typical

The same name for all shards

name: blob-report. v4 artifacts are immutable: a second shard trying to upload the same name fails with a conflict, and part of the blobs is lost.

Better

The shard index in the name

blob-report-${{ matrix.shardIndex }}. Each shard has its own name, and the merge takes everything by the blob-report-* pattern.

Figure 3. A unique artifact name per shard is mandatory, otherwise the report is incomplete.

Fast reruns. --last-failed reruns only the tests that failed in the previous run, and --only-changed runs test files changed relative to HEAD or a given branch, plus those that import changed files (--only-changed=origin/main). On CI, comparing with a branch needs git history: actions/checkout with the default shallow clone may not have it, so fetch-depth: 0 is added. The first is handy locally after a failure, the second gives fast feedback in a PR. They do not replace a full run before the merge: a change in the app can break a test whose file did not change.

The same image locally. To reproduce a CI failure or generate screenshot baselines, the image is run on your own machine too:

docker run --rm --network host --ipc=host -v $(pwd):/work -w /work -it \
  mcr.microsoft.com/playwright:v1.65.0-noble /bin/bash
# inside: npm ci && npx playwright test checkout.spec.ts

--ipc=host is recommended for Chromium so that shared memory in the container does not run out. This way a local run uses the same fonts and libraries as the pipeline.

Limits and alternatives. Sharding shortens the run time but does not cure unstable tests and does not reduce the amount of work: the total runner minutes grow. There should be no more shards than is useful: each one has to install dependencies and bring up the environment, so overhead quickly eats the gain. An alternative within Playwright: shrink the set run in a PR with --only-changed or tags. For comparison, in Cypress the split between machines comes from Cypress Cloud: it hands out specs dynamically, by the duration of previous runs, not by a fixed list. In Selenium you build sharding yourself, through Grid and distribution in CI.

Common mistakes.

  • The same artifact name in all shards: jobs fail with a conflict, and the report is incomplete.
  • An image of a different version than in package.json: the browser is not found or the render differs from screenshot baselines.
  • Merging the report without !cancelled(): when a shard fails there is no report exactly when it is needed.
  • Default fail-fast: the first failed shard cancels the rest, and you see only part of the problems.
  • --only-changed as the only run: a change in the app breaks a test whose file did not change, and nobody sees it until the merge.

Check yourself

One of the four shards failed, and the pipeline has no HTML report. What do you check in the job configuration?

Answer

Whether the merge job has if: ${{ !cancelled() }} (by default a job is skipped when a job in its needs failed) and whether fail-fast is off so the other shards finish. Also whether shard artifacts are uploaded under !cancelled() and not only on success.

Five files take 2 minutes each, one takes 20. Without fullyParallel there are four shards. Why does the run still take 20+ minutes?

Answer

Without fullyParallel the unit of the split is a file, and the big file falls entirely into one shard. With fullyParallel: true its tests would be spread across shards.

In a PR tests run with --only-changed=origin/main and fail with an error about a missing branch. What is wrong with the checkout?

Answer

A shallow clone has no history of the main branch, so there is nothing to compare with. You need fetch-depth: 0 in actions/checkout or an explicit fetch of that branch.

In an interview. Junior: On CI I split the run into shards with --shard and assemble the reports from blobs into one HTML. Middle/Senior: I run tests in the official Docker image of the same version as @playwright/test, split with a matrix using fail-fast: false and unique artifact names, and merge the report through merge-reports under !cancelled(). fullyParallel balances the shards, and --only-changed gives fast feedback in a PR, but a full run stays before the merge.