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

Playwright

Debugging, trace viewer, reports, flaky tests

Diagnostics: trace viewer, reports, flaky tests

A CI failure is investigated with a trace: a trace.zip archive with an action log, DOM snapshots, network, console and the test source. A snapshot is restored as a live page, so a locator and server responses can be checked. on-first-retry is cheap but records only the first retry, so retain-on-failure is used for flaky tests. A trace is not attached to public tickets without cleaning.

Playwright · Debugging

A test is red on CI, green locally, and the log is one line. What can you learn from it?

Payment passes on a laptop and fails on CI. The log has a single line: "Timeout 5000ms exceeded". The report screenshot explains nothing: the button is there, the order status says "Processing". Without a record of what happened you can only guess. This lesson covers what Playwright records, how to keep it and read it, and how to tell a flaky test from a broken application.

How it works and why. The browser on CI dies together with the test, there is no screen, and the failure cannot be repeated on demand. So Playwright records not a video but a trace: a trace.zip archive with an action log and page snapshots. For every action (click, fill, navigation, assertion) it stores DOM snapshots before, during and after it, plus network requests with response bodies, console messages, page errors and the test's source code with the line highlighted. A snapshot is rebuilt from the recorded DOM and resources, so it is a live page: you can hover, open DevTools, copy text and check a locator on the Locator and Pick locator tabs. A video cannot do that: you cannot click it or see what the server answered.

Recording is not free: DOM snapshots slow a run down and take space. So the trace mode decides when to record and what to keep:

Where a trace comes from with retries

Attempt 1 failsno trace is recorded yet Retry 1: trace is onactions, DOM and network recorded test-results/…/trace.zipnext to the screenshot and error retry is greenflaky mark retry is redfailed + trace
Figure 1. The on-first-retry mode: the first attempt stays without a trace, recording starts with the first retry.
Trace modeWhat happensWhen to use
on-first-retryRecords only the first retryCI with retries, the cheapest option
retain-on-failureRecords every attempt, deletes green onesHunting flakiness, when the first failed attempt is what you need
on-all-retriesRecords every retryWhen the second retry fails too
onRecords and keeps everythingLocal investigation of a single test

Example: from a log line to the cause. A config with no artifacts, and a test that fails only on CI:

// before: no retries and no trace, only the error text
export default defineConfig({
  retries: 0,
});
Error: expect(locator).toHaveText(expected) failed

Locator: getByTestId('order-status')
Expected string: "Paid"
Received string: "Processing"
Timeout: 5000ms

(The error is shortened.) It shows that the assertion waited five seconds and the text did not change, but not why. Turn the artifacts on:

// after
export default defineConfig({
  retries: process.env.CI ? 2 : 0,
  use: {
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
});

After the run, open the trace from the HTML report (npx playwright show-report) or from a file: npx playwright show-trace test-results/…/trace.zip. The same file can be loaded at trace.playwright.dev: the viewer runs in the browser, and the data is not sent to a server. Read top to bottom. In the action log the click on "Pay" is green. On the Network tab the POST to the payment endpoint went out at once, and the response arrived about seven seconds later (in this example). The assertion waits only five. So the test is not "wrong" and the locator is right: the application on CI is slower than the wait limit.

// fix: wait for the concrete response, then check the UI
const paid = page.waitForResponse(
  (r) => r.url().includes('/api/payments') && r.ok(),
);
await page.getByRole('button', { name: 'Pay' }).click();
await paid;
await expect(page.getByTestId('order-status')).toHaveText('Paid');

A longer pause or waitForTimeout would be worse: the first hides the cause, the second wastes time on fast runs. And a seven-second response is itself a signal for the backend team.

What to do with a rerun

Typical

Rerun and forget

The pipeline is green, the cause is unknown. Next week it fails again, and the report only says flaky.

Better

A retry as a signal

The retry saves the pipeline, while the flaky mark and the trace become a task: read the record and fix the cause.

Figure 2. Retries exist so that one glitch does not stop the team, not to hide instability.

How to read a trace by symptom.

SymptomWhere to look
Element not foundThe "before" snapshot on the action tab: is the element there, did a modal cover it, is the text different (language, case)
An assertion did not get its resultNetwork: was the request sent, with what status and how long it took; Console: was there an error in the application
A click did not workThe action log: which wait check failed (covered, disabled, moving)
Wrong dataThe response body on the Network tab and the Source tab with the test line

Anatomy of an error: a click on a disabled button

1Error: locator.click: Test timeout of 30000ms exceeded.
Call log:
2- waiting for getByRole('button', { name: 'Pay' })
  - locator resolved to <button disabled class="pay">
3- waiting for element to be visible, enabled and stable
  - element is not enabled
  - retrying click action
4at checkout.spec.ts:24:31
  1. What: click did not fit into the test limit, 30 s. That is the consequence, not the cause.
  2. Element found: the locator worked, no need to change it.
  3. Why: the button stayed disabled and Playwright kept waiting for it to become enabled.
  4. Where: line 24 of the test. Start here: what was supposed to enable the button?

What to do

Find out why the form is not ready (an empty field, a request still running) and check it explicitly: await expect(pay).toBeEnabled(). Not force: true: it hides the bug.

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

Limits and alternatives. A trace does not see server logs or database state: if a request returned 500, the cause is on the backend, and the trace only proves it. For flakiness on the very first attempt on-first-retry is not enough: if the first attempt failed and the retry passed, the trace is of a green run and the failed attempt is not visible. Then take retain-on-failure. A trace may contain cookies, authorization headers and response bodies, so do not attach it to public tickets without cleaning. In Cypress a similar role is played by Test Replay in Cypress Cloud (the run's DOM, network and console), in Selenium artifacts are collected by hand (screenshots, driver logs): there is no ready record of actions with the DOM.

Reports. The built-in HTML one is for people, list and dot for the console, JUnit for CI systems, github for annotations in a PR, blob for shards, and Allure works through a separate package. A test that passed only after a retry is marked flaky by the HTML report. The full set of artifacts and reporter settings is in the lesson “Artifacts and reports”.

Common mistakes.

  • on-first-retry without retries: there are no retries and no trace, and you have to guess the cause.
  • trace: 'on' in a large suite: gigabytes of artifacts and a slower CI.
  • Not uploading the report as a CI artifact (a step without if: always() or !cancelled()): after a failure there is neither a report nor a trace.
  • Treating a retry as the fix: the test is green but the instability stays and returns at the worst moment.
  • Adding secrets to report attachments: the whole team sees them.

Check yourself

The config has trace: 'on-first-retry' and retries: 0. A test failed on CI. Will there be a trace?

Answer

No. The mode records only the first retry, and there are no retries, so nothing is recorded. Either turn retries on or take retain-on-failure, which records every attempt and keeps only the failed ones.

A test is marked flaky: attempt 1 failed, attempt 2 passed. With on-first-retry you open the trace. What is in it and why may that not be enough?

Answer

The trace belongs to the first retry, which passed, so it holds a green run. Failed attempt 1 has no recording: only the error text and a screenshot. To study the instability itself you need retain-on-failure, which keeps the trace of every failed attempt.

In the trace the click on "Pay" is green, but on the Network tab the payment response has status 500, and the assertion waited for "Paid". Is the cause in the test or in the application?

Answer

In the application or the environment: the test clicked correctly and waited correctly, and the backend returned an error. Raising the timeout is useless. Next you look at the response body, the server logs and the data the test used.

In an interview. Junior: I investigate a CI failure through the trace: it shows every action, page snapshots, network and console. On CI I set trace: 'on-first-retry' together with retries. Middle/Senior: I pick the mode for the task: on-first-retry is cheap, but for a flaky test it gives only the green retry, so for an investigation I take retain-on-failure. I read the action log, then Network and Console, and that is how I tell a slow backend from a bad locator. I do not count retries as a fix: I watch the flaky mark and fix the cause. A trace may contain tokens, so I do not add it to public tickets without cleaning.

Local debugging: the tools and when to use which

The local debugging tool depends on the moment: UI mode for writing tests, Inspector for stopping, trace for a failure that already happened. To stop before an action use --debug or page.pause(), and pick a locator with Pick locator or codegen. These need a screen, so on CI without a display the trace is used. Adding pauses instead of looking at the page does not help.

Playwright · Debugging

A test fails on step five. How do you stop right there and check the locator?

A test fails on step five with "element(s) not found". The first four steps work. The easiest move is to add waitForTimeout and run again, but that shows nothing. Playwright has a set of tools, and each answers its own question: what is on the page now, which locator fits, what the library is doing, and what happened while I was not looking. This lesson covers which to take in which situation.

How it works and why. All the tools rest on one thing: the browser is driven through a protocol, so from outside you can stop it, look at a DOM snapshot or try a locator without changing the test. That gives three moments to step in: before the run (record steps, pick a locator), during it (stop and step through) and after it (analyse a recording).

Three moments, three tools

Writing a testUI mode, codegen, VS Code extension Standing on a step--debug, page.pause(), Inspector Already failed, including on CItrace viewer, HTML report
Figure 1. The tool depends on when you step in. On CI only the third is available: there is no interactive screen there.
TaskTool
Write a test and rerun it quicklyUI mode, --ui
Stop before a specific action--debug, page.pause()
See what is happening in the browser--headed, slowMo
Pick a locatorPick locator, codegen
Investigate a failure from CItrace viewer
See what the library itself is doingthe DEBUG=pw:api variable
  • npx playwright test --ui: UI mode. A list of tests, watch mode (rerun when a file changes), time travel through steps with DOM snapshots, network and console, locator picking on a snapshot. The main tool while writing tests.
  • --debug: a shortcut for Playwright Inspector. It turns on headed mode and a single worker and disables the test timeout, so the clock does not stop you. A specific line can be launched like this: npx playwright test login.spec.ts:12 --debug.
  • await page.pause(): a breakpoint in code that opens the Inspector right here.
  • --headed and launchOptions: { slowMo: 300 }: watch the flow at a slowed-down pace.
  • The VS Code extension: running a single test, breakpoints, the Pick locator button with a locator suggestion.

Example: a locator does not find a row. The test fails, and the temptation is one: add a pause.

// before: guessing that the row "has not arrived yet"
await page.goto('/transactions');
await page.waitForTimeout(3000);
await expect(page.getByRole('row', { name: /Transfer/ })).toBeVisible();
Locator: getByRole('row', { name: /Transfer/ })
Expected: visible
Received: <element(s) not found>
Timeout: 5000ms

(The error is shortened.) Instead of a third second of pause, stop the test before the assertion and look at the page:

await page.goto('/transactions');
await page.pause(); // the Inspector opens, then steps by hand

In the Inspector switch on Pick locator and click the row. It suggests getByText('Money transfer'), not getByRole('row', …). That is the diagnosis: the rows in the application are div elements without the row role, so a role locator finds nothing however long it waits. A pause would have changed nothing.

// after: a locator that matches the real markup
const rows = page.getByTestId('tx-row').filter({ hasText: 'Transfer' });
await rows.first().highlight(); // highlight in the browser: is it the one?
await expect(rows).toHaveCount(3);

The highlight() method highlights the element in the open browser, so you check the locator with your eyes before the commit goes further. Remove page.pause() before committing.

Extra diagnostics. DEBUG=pw:api npx playwright test prints every API call, wait and retry of a check to the console: useful when it is unclear what exactly the test "hangs" on. Switch slowMo on with a variable so that a slowed-down run is not committed by accident:

// playwright.config.ts
use: {
  launchOptions: { slowMo: process.env.SLOW ? 300 : 0 },
},

Codegen is useful for more than recording actions:

npx playwright codegen --device="iPhone 13" https://app.test
npx playwright codegen --save-storage=auth.json https://app.test/login
npx playwright codegen --load-storage=auth.json https://app.test/dash

The first command opens the application with device emulation, the second saves the state after a manual login, the third opens it already logged in. The generated code is not committed as is: you take the locators from it and rewrite the structure into fixtures and a Page Object.

A flaky test and slow motion

Typical

Debug a flaky test headed with slowMo

Slowing down gives the application time to load everything. The race that fails on a fast CI disappears and the test "works".

Better

Repeat at CI speed and take a trace

A headless run with --repeat-each and a recorded trace reproduces the real conditions and keeps a record of the failed attempt.

Figure 2. Stopping tools show a state but do not reproduce races: instability needs repeats and a recording.

Limits and alternatives. The Inspector, UI mode and headed mode need a screen, so they are unavailable on an ordinary CI without a display: there the trace and other artifacts work. Headed and headless behave almost the same, but differences happen (window size, fonts, rendering), so to investigate a CI failure it is more reliable to reproduce the environment with the same Docker image. In Cypress the analogue of UI mode is the interactive runner with time travel, in Selenium you stop with an ordinary IDE debugger, and there is no DOM snapshot "before" and "after" each action.

Common mistakes.

  • Committing page.pause(). In headless mode the call does nothing, but in a headed run (locally or on CI with a virtual display) it stops the test, so it stays a trap. A linter rule for this call (for example no-restricted-syntax) catches such cases.
  • Debugging a flaky test only headed with slowMo: slow motion hides races that show up on a fast CI.
  • Trusting a codegen selector without checking: it may hold on to text or structure that changes.
  • Adding pauses instead of looking at the page: "element not found" is more often a locator problem than a timing one.

Check yourself

The Inspector did not open for page.pause(): the test passed on CI and nothing stopped. Why?

Answer

page.pause() works only in headed mode. In a headless run (an ordinary CI) the call is ignored. That is why a trace, not a pause, is used to investigate a CI failure.

Pick locator suggested getByText('Money transfer'), while the test uses getByRole('row', { name: /Transfer/ }) and fails with "not found". What does that say about the page?

Answer

The element exists, but most likely it has no row role (it is a div without ARIA markup). Waiting will not help here: a role locator will never find it. Change the locator (a test id with filter) or add semantics to the application.

In an interview. Junior: While writing tests I work in UI mode, and to stop on a step I use page.pause() or --debug and pick a locator with Pick locator. Middle/Senior: The tool depends on the moment: UI mode for writing, the Inspector for stopping, the trace for what has already failed on CI, where there is no screen. For flaky tests I do not rely on headed and slowMo, because they hide races: I repeat at CI speed with --repeat-each and a recorded trace. I rewrite code from codegen into fixtures and take only the locators from it.

Artifacts and reports

Artifacts are the traces, screenshots, videos and reports left from a run once the browser is gone. A typical CI setup is trace on-first-retry with retries, screenshots only on failure, and video only where needed. The report upload runs under always() or !cancelled(), otherwise it is skipped after the tests fail. Playwright clears the test-results folder at the start of every run.

Playwright · Debugging

The test is red on CI and the report is empty: no trace, screenshot or video. What went wrong?

A test failed on CI, the developer opens the pipeline and finds neither a report nor a trace: the upload step did not run because the previous one was red. Artifacts are everything that remains of a run when the browser is gone: traces, screenshots, videos, reports, attached data. They are configured on the principle "enough to investigate, but no more expensive than needed": recording every trace across thousands of tests slows the run down and fills the storage. This lesson covers what Playwright creates, where it puts it and how to make sure it survives a failure.

How it works and why. There are two different places. Test artifacts (traces, screenshots, videos) go to outputDir, test-results by default, into a separate subfolder per test and attempt. Playwright cleans this folder at the start of every run, so old results do not pile up, but they do not survive the next run either. Reporters write separately: the HTML reporter to playwright-report, JUnit to the file you name, blob to blob-report. The report and results folders must be different. The HTML reporter copies the tests' traces, screenshots and videos into the report's data subfolder, so the playwright-report folder is self-contained: it can be uploaded and opened apart from test-results.

The path of an artifact from a test to a developer

A test runuse: trace, screenshot, video test-results/cleaned at the start of every run Reportershtml, junit, blob, github An upload step with always()artifacts stay available after a failure
Figure 1. A test creates files, reporters build reports, and they survive a failure only if a separate step uploads them.

What to record. It is configured in use:

OptionUseful valuesCost
traceon-first-retry, retain-on-failure, onMedium: DOM snapshots
screenshotonly-on-failure, onLow
videoretain-on-failure, on-first-retryHigh: the heaviest artifact

on-first-retry writes an artifact only on the first retry, so without retries it gives nothing. retain-on-failure always writes but keeps only for failed tests: more expensive, but the artifact exists even without retries. A typical CI scheme: trace: 'on-first-retry' and screenshot: 'only-on-failure', with video switched on selectively. The trace option also accepts an object if you need to control what is recorded:

use: {
  trace: { mode: 'retain-on-failure', screenshots: true, snapshots: true, sources: true },
  video: 'retain-on-failure',
},
outputDir: 'test-results', // traces, videos and screenshots go here

Example: the report vanished together with the failure. A step without a condition:

# before: after a red tests step this step will not run
- run: npx playwright test
- uses: actions/upload-artifact@v4
  with:
    name: playwright-report
    path: playwright-report/

By default a step runs only if all previous ones succeeded. The test failed, the upload step was skipped, and the pipeline is red with no artifacts at all. The fix is a condition that runs the step always:

# after: upload the report and the results always
- run: npx playwright test
- uses: actions/upload-artifact@v4
  if: always()
  with:
    name: playwright-report
    path: |
      playwright-report/
      test-results/
    retention-days: 14

Instead of always() people often take !cancelled(): artifacts are kept, and a manually cancelled run does not waste time uploading. The retention period (retention-days) keeps the storage under control. If there are many tests split into shards, each shard uploads a blob report under a unique name and a separate step merges them with merge-reports; that is covered in the lesson “CI: sharding, Docker and fast reruns”.

The upload step after tests fail

Typical

No condition

The tests step is red and the next ones are skipped. There is no report or trace, and the investigation starts with a rerun.

Better

With always()

The upload runs after a failure: the report and trace wait in the pipeline for the developer to open them.

Figure 2. A report is needed exactly when tests failed, so its upload step must not depend on success.

Reporters. Several can be used at once, and the set depends on the environment:

reporter: process.env.CI
  ? [['blob'], ['junit', { outputFile: 'results/junit.xml' }], ['github']]
  : [['html', { open: 'on-failure' }], ['list']],
ReporterWhat it is for
htmlA report for people with traces, screenshots and a flaky filter
list, dotConsole output
junitIntegration with Jenkins, GitLab and other CI systems
githubError annotations right in the PR
blobA shard report for later merging

For Allure you add the allure-playwright package.

Your own data in the report. Through testInfo.attach you add everything that helps investigate a failure: API responses, logs, generated files. A file from disk is attached with the path parameter instead of body.

test('statement reconciliation', async ({ request }, testInfo) => {
  const res = await request.get('/api/statement');
  await testInfo.attach('statement', {
    body: await res.text(),
    contentType: 'application/json',
  });
  expect(res.ok()).toBeTruthy();
});

Steps. test.step groups actions in the report and the trace under clear names, so a long scenario reads as a set of business steps, and a failure highlights exactly the step where the test stopped:

await test.step('The client submits a request', async () => {
  await page.getByRole('button', { name: 'Submit' }).click();
  await expect(page.getByText('Request accepted')).toBeVisible();
});

Limits and alternatives. Artifacts do not replace server logs: they show what the browser saw. Video takes the most space and gives the least: the trace shows the same with the DOM and network, so video is switched on when a failure has to be shown to people outside the team. In Cypress, cypress run keeps screenshots on failure by default, while video is turned on with video: true, in Selenium artifacts are collected by your own code in hooks.

Common mistakes.

  • trace: 'on' in a large suite: gigabytes of artifacts and slower runs.
  • on-first-retry without retries: there are no artifacts, and the developer does not understand why.
  • An upload step without always() or !cancelled(): the report disappears exactly on a failure.
  • The same artifact name in all shards: they overwrite each other.
  • Attaching secrets (tokens, passwords): the whole team sees the report.

Check yourself

The npx playwright test step is red. The next step uploading playwright-report has no condition. What will happen in the pipeline?

Answer

The upload step will not run: by default the following steps start only after successful ones. There will be no report or trace in the pipeline, exactly what had to be saved. Add if: always() or !cancelled().

You run the tests twice in a row locally and notice that the trace of the first run has vanished from test-results. Is it a bug?

Answer

No. Playwright cleans outputDir at the start of every run. If a result has to be kept, copy it elsewhere or upload it as a CI artifact before the next run.

Why is retain-on-failure better for a long flaky scenario, while video is switched on only selectively?

Answer

retain-on-failure keeps the trace of every failed attempt, including the first, and keeps only those, so no space is wasted. Video is the heaviest, and a trace with the DOM and network allows a more precise investigation, so video is taken when a failure has to be shown to people outside the team.

In an interview. Junior: On CI I set trace: 'on-first-retry' with retries, screenshots only on failure, and I upload the report and test-results with a separate step using always(). Middle/Senior: The reporter set depends on the environment: blob for shards with later merging, JUnit for the CI system, github for PR annotations, HTML locally. I do not make artifacts more expensive than needed: video only selectively, retention-days limited, shard artifact names unique. I attach extra data such as API responses through testInfo.attach, but never secrets, because the whole team sees the report.

How I systematically investigate a flaky test

A flaky test is investigated as a search for the cause: reproduce the raw failure rate without retries and narrow the hypotheses one by one. The sources are few: time, shared state, order, environment and real application races; compare --workers=1 with several workers and a red trace with a green one. Until fixed, the test is quarantined with an owner and a deadline; force: true and long pauses cure nothing.

Playwright · Debugging

A test fails once in ten runs and the code has not changed. Where do you start?

The payment test passes nine times out of ten. The team already reruns the pipeline out of habit, and red is no longer taken as a signal. That is the real harm of flakiness: not one red run but the loss of trust in the whole suite. "Just rerun it" is not an answer; an answer is a process that leads from a symptom to a cause in predictable time. Below is such a process and an example where a second cause remains after the first is fixed.

How it works and why. A test is unstable when its result depends on something it does not control. There are few such sources: time (a response came earlier or later, an animation did not finish), shared state (data or an account touched by another test or worker), order (a test relies on leftovers of the previous one), the environment (CI is slower, a different font, time zone or browser version) and real races in the application itself. The investigation is built as a narrowing of hypotheses: each step rules out one source.

How the search for the cause narrows

1 Reproduce--repeat-each=20 --retries=0 2 Isolation--workers=1 versus --workers=4 3 Orderalone with -g, then in the suite 4 Trace: red versus greenwhat differs: timing, data, state 5 Classify the causetest, data, environment, app bug
Figure 1. Each step rules out one source of instability, so the cause is found in a few runs rather than by guessing.

Example: two layers of one problem. First reproduce without retries to see the raw failure rate:

npx playwright test checkout.spec.ts --repeat-each=20 --retries=0
npx playwright test checkout.spec.ts --repeat-each=20 --retries=0 --workers=1
npx playwright test checkout.spec.ts --repeat-each=20 --retries=0 --workers=4
npx playwright test -g "card payment" --repeat-each=30 --retries=0 --trace on

Suppose with one worker it fails in 3 runs out of 20, and with a shared account and four workers more. These are two signals. The first, failing even sequentially, points to waiting. Compare the trace of a red and a green run: in the red one the API response arrived in three seconds, in the green one in half a second. Meanwhile the test reads the status once:

// before: a fixed pause and a one-time check of the state
await page.getByRole('button', { name: 'Pay' }).click();
await page.waitForTimeout(2000);
expect(await page.getByTestId('order-status').textContent()).toBe('Paid');
// after: a web-first assertion that retries until the timeout
await page.getByRole('button', { name: 'Pay' }).click();
await expect(page.getByTestId('order-status')).toHaveText('Paid');

The first variant either wastes two seconds or does not make it when the backend is slower. The second waits exactly as long as needed. Likewise waitForLoadState('networkidle') is not recommended: applications with polling or analytics do not "go quiet". It is better to wait for a visible result or a specific response through page.waitForResponse.

The second layer: with four workers the test still fails sometimes, because all workers log in with one account and empty one cart. Data isolation per worker through a fixture:

export const test = base.extend<{ account: string }>({
  account: async ({}, use, testInfo) => {
    // an own account per worker: parallelIndex is stable within a run
    await use('qa-user-' + testInfo.parallelIndex + '@test.com');
  },
});

After both fixes repeat --repeat-each=20 on one and on four workers: zero failures on both. A single green run is not enough, because instability returns at random.

Typical causes and what to do.

SymptomProbable causeFix
An element is "not clickable" or coveredAn animation, a spinner, a modalWait for the state with a web-first assertion, not force: true
Fails only in parallelShared data or accountData per test or worker through a fixture
Passes alone, fails in the suiteOrder dependence, leftoversIndependent tests, a clean state
Fails only on CIA slow environment, a different font or time zoneThe same image, explicit waits
Fails randomly on a valueTime-dependent or random dataFix the time (page.clock) and the data

The last cause matters: some flaky tests are real bugs that a user will also meet. If a double click creates two payments, it is not a test problem but a race condition in the application, and that is what must be fixed.

Quarantine. Until the cause is fixed, the test must not block the team. It is moved into a quarantine project with a tag that does not block the merge. The alternative test.fixme skips the test completely, whereas in quarantine it keeps running and gives statistics:

test(
  'card payment',
  { tag: '@quarantine', annotation: { type: 'issue', description: 'QA-482' } },
  async ({ page }) => {
    // …
  },
);

// playwright.config.ts
projects: [
  { name: 'stable', grep: /^(?!.*@quarantine)/ },
  { name: 'quarantine', grep: /@quarantine/, retries: 3 },
],

How not to block the team while a test is unstable

Typical

Raise retries for everything

Less red, but nobody sees the instability and the pipeline gets slower. A month later there are twice as many flaky tests.

Better

Quarantine with a ticket, an owner and a deadline

The test does not block the merge, its failures are counted, and the owner knows when to return it to stable.

Figure 2. Quarantine is a temporary status with an owner and a date, not a dumping ground.

Limits and alternatives. The algorithm finds a cause only if the failure reproduces. If a test fails once in a hundred CI runs and never locally, you go for reproducing the environment (the same Docker image, CPU limits, parallelism as on CI) and for retain-on-failure, so that the trace of the first failure is not lost. For control at the level of the whole suite there is the failOnFlakyTests option, which makes the run red if any test passed only after a retry: turn it on when the team is ready to tolerate no flakiness. A metric worth tracking is the share of flaky tests in runs: the HTML report marks such a test separately. In Cypress a similar role is played by cloud detection of flaky tests, in Selenium you have to find flaky tests from CI history yourself.

Common mistakes.

  • Raising retries instead of looking for the cause: the instability stays, but the report is silent.
  • force: true or long pauses as a "cure": the test stops checking what a user sees.
  • Starting an investigation with --retries: a retry hides the failure you are looking for.
  • Quarantine without an owner and a deadline: half a year later it holds hundreds of tests nobody checks.
  • Fixing the symptom in the test when the cause is in the application: the bug reaches users.

Check yourself

A test passes alone through -g but fails in the full suite. Which hypothesis do you check first, and how?

Answer

Order dependence or leftover data: a previous test leaves a state this one relies on. Check it by running the test after a specific neighbour, looking at the data in the trace, and make the tests independent (a clean state per test through a fixture).

With --workers=1 the test is green 20 times, with --workers=4 it turns red. What does that say about the cause?

Answer

The problem is shared state between workers: the same account, data or file. Each worker needs its own data, for example through a fixture with testInfo.parallelIndex. Longer waits will not help here.

Why is the investigation run with --retries=0 although retries are on in CI?

Answer

A retry hides the first failure: the test is marked flaky and passes. To see the raw failure rate and compare changes before and after a fix, retries are turned off for the duration of the investigation.

In an interview. Junior: I do not rerun a flaky test blindly: I repeat it with --repeat-each, look at the trace of the failure and look for the cause, such as an unneeded pause or shared data. Middle/Senior: I narrow hypotheses: the raw failure rate without retries, then isolation by changing the number of workers, order by running the test alone, a comparison of the trace of a red and a green run. I classify the cause: the test, data, environment or a real race condition, because some flaky tests are bugs a user will see. Until it is fixed the test goes into quarantine with a ticket, an owner and a deadline, and I track the share of flaky tests separately.