| | |

Vitest 28 🧪 Playwright Traces — Debugging browser tests with trace files

⏱️ Estimated read: 15 min | |

A Playwright trace is a recorded timeline of everything that happened during a browser test: the actions taken, the DOM snapshots before and after each action, the network requests, the console output, and the screenshots. When a test fails in CI and the failure is not reproducible locally, the trace is the artifact that turns an opaque “expected true, received false” into a visible sequence of steps. Vitest does not implement traces itself; when a test runs in browser mode through the Playwright provider, the provider records the trace and stores it in a trace file, and the Playwright Trace Viewer replays it.

This chapter covers what a trace contains, how Vitest’s browser mode enables tracing through the Playwright provider, where the trace files land in the output directory, and how to open and read one with the Trace Viewer. It also covers the practical decisions: when to record, how to record only on failure to keep CI artifacts small, and how the trace’s DOM snapshots relate to the test’s assertions. The sections that follow walk through the trace’s anatomy, the configuration that turns recording on, and the workflow for reading a trace after a failure.

Key point: A Playwright trace is a self-contained recording of a browser test’s actions, DOM snapshots, network activity, and console output, produced by the Playwright provider when Vitest runs in browser mode and replayed with the Playwright Trace Viewer; it is the primary debugging artifact for a browser test that fails in CI, and it should be configured to record on failure so the artifact is captured exactly when it is needed without bloating the output of passing runs.


Why traces exist

The CI-only failure problem. A browser test that passes locally and fails in CI is the hardest class of failure to debug, because the local environment cannot reproduce it. Without a trace, the only artifacts are the assertion message and, at best, a screenshot of the final state. The trace records the entire timeline, so the failure’s preceding actions, the DOM state at each step, and the network responses that drove the state are all visible after the fact.

The asynchronous DOM problem. A browser test’s failure is often a timing issue: the assertion ran before the DOM settled, or an action targeted an element that was re-rendered between the locator resolution and the click. A single final screenshot cannot show this. The trace’s per-action DOM snapshots show the page before and after each step, and the timeline shows the gaps between actions, which is where timing bugs live.

The network dependency problem. A test that fails because a request returned a different payload, or because a request never fired, is invisible in an assertion message. The trace records the network log alongside the actions, so the request, its response, and the moment it resolved are aligned with the DOM snapshot that depended on it.

The console error problem. A page error thrown by the application—an unhandled rejection, a failed hydration, a missing asset—often surfaces only as a console message while the test’s assertion fails for a different, downstream reason. The trace captures the console and page errors in the same timeline, so the root cause is visible next to its symptom.

The reproduction cost problem. Re-running a flaky browser test in CI to capture more output is expensive and unreliable, because the failure may not recur. A trace is recorded during the run that failed, so the evidence exists without a reproduction attempt.

The trade-off. Tracing has a cost: the trace file grows with the test’s length and the number of DOM snapshots, and recording every test on every run produces large artifacts. The standard compromise is to record on failure only, or to record on the first retry, so passing runs stay cheap and failing runs produce the full evidence.


a. What a Playwright trace contains

A trace is a directory or a zip archive depending on the recording mode, containing a set of files that the Trace Viewer assembles into a timeline. The Viewer presents four aligned panels: the actions, the DOM snapshot, the source, and the metadata, plus tabs for the network log and the console.

The actions panel lists every action the test performed—click, fill, goto, expect—in order, with the time each took and whether it succeeded or failed. Each action is a row in the timeline, and selecting it moves the DOM snapshot panel to the state at that moment.

// The actions a trace records for this test:
// 1. goto("/login")          — navigation
// 2. fill("#email", ...)     — input
// 3. fill("#password", ...)  — input
// 4. click("button[type=submit]") — submit
// 5. expect(page).toHaveURL("/dashboard") — assertion
await page.goto("/login");
await page.fill("#email", "alice@example.com");
await page.fill("#password", "secret");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/dashboard");

The DOM snapshot panel is the state of the page at the selected action. The snapshots are not screenshots; they are serialized DOM trees that the Viewer renders, so the Viewer can show the page as it was and highlight the element the action targeted. Hovering a selector in the actions panel highlights the matching element in the snapshot.

// The snapshot at the `click` action shows the form
// with both fields filled, and the button in its enabled
// state — the exact state the click targeted.
// The snapshot at the failed `expect` shows the URL
// still on /login, which is the failure's evidence.

The source panel shows the test’s source lines around the selected action, so the trace maps each timeline row back to the code that produced it. The network tab lists every request and response with status, timing, and body, aligned to the same timeline. The console tab lists the page’s console messages and uncaught errors.


b. Enabling traces in Vitest browser mode

Traces are a Playwright provider feature. Vitest’s browser mode selects a provider, and the playwright provider is the one that supports tracing. The provider is configured in the test.browser section of the Vitest config, and the launchOptions and contextOptions that Playwright accepts are passed through.

// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: "playwright",   // the provider that records traces
      instances: [{ browser: "chromium" }],
    },
  },
});

The trace recording itself is a Playwright context option, trace, and Vitest passes the provider’s contextOptions through to the browser context it creates. The value is one of "off", "on", or "retain-on-failure", and the "retain-on-failure" value is the one that records during the test and keeps the trace only if the test fails.

// vitest.config.ts — record on failure only
export default defineConfig({
  test: {
    browser: {
      provider: "playwright",
      instances: [
        {
          browser: "chromium",
          contextOptions: {
            // Record the trace, discard it if the test passes
            trace: "retain-on-failure",
          },
        },
      ],
    },
  },
});

The "retain-on-failure" value is the production setting. The trace is recorded for every test, but only the failing test’s trace is written to disk, so passing runs produce no artifacts and failing runs produce exactly the trace that explains the failure. The "on" value writes a trace for every test and is useful for a short local investigation, but it produces one trace per test and is too expensive for a full CI run.

// The three trace modes
// "off"                — no recording
// "on"                 — record and keep every trace
// "retain-on-failure"  — record, keep only on failure

The trace file location is the output directory the provider uses. Vitest writes the provider’s artifacts under the configured output directory, and the failing test’s trace is named after the test so the failing run’s artifact is identifiable in the CI logs.


c. Reading a trace with the Trace Viewer

The Trace Viewer is a local web application that opens a trace file and renders the timeline. The command is npx playwright show-trace, and the argument is the path to the trace file or the directory that contains it.

# Open a specific trace file
npx playwright show-trace test-results/login-failure/trace.zip

# Open the viewer and drop a trace file onto it
npx playwright show-trace

The viewer’s layout mirrors the trace’s structure: the actions list on the left, the DOM snapshot in the center, and the source, network, and console in the panels that open on selection. Selecting a failed action highlights it in red, and the snapshot panel shows the DOM at that moment, which is the state the assertion saw.

// The trace viewer's reading order for a failed assertion:
// 1. Select the failed action in the actions list.
// 2. Read the DOM snapshot — what was on the page.
// 3. Read the console — did the app throw?
// 4. Read the network — did the expected request fire?
// 5. Step back one action — what set up the failing state?

The snapshot’s before/after toggle is the viewer’s key affordance. Each action has a “before” snapshot and an “after” snapshot, and toggling between them shows exactly what the action changed. A click that should have navigated but did not shows an identical before and after, which localizes the bug to the click’s effect rather than the assertion.

The time-travel feature is the other key affordance. The viewer’s timeline is scrubbable, so the state between actions is visible. A request that resolved slowly, a spinner that appeared and disappeared, and a re-render that replaced the targeted element are all visible between the action rows, which is where timing bugs are found.

The metadata panel shows the test’s title, the browser and its version, the viewport, and the trace’s recording settings. That metadata is what makes a CI trace actionable: the browser version and viewport are the environment that produced the failure, and they are the first things to compare when the failure does not reproduce locally.

// The failure workflow with a trace:
// 1. Open the failing test's trace from the CI artifact.
// 2. Select the failed action; read the DOM snapshot.
// 3. Read the console for an app error.
// 4. Read the network for the missing or wrong response.
// 5. Compare the metadata's browser version to local.
// 6. Reproduce locally with the same browser and viewport.

Complete Example Session

// ============================================
// PART 1: THE CONFIG WITH TRACE ON FAILURE
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: "playwright",
      instances: [
        {
          browser: "chromium",
          contextOptions: {
            trace: "retain-on-failure", // keep only failing traces
          },
        },
      ],
    },
  },
});

// ============================================
// PART 2: THE TEST THAT PRODUCES THE TRACE
// ============================================
import { test, expect } from "vitest";
import { page } from "@vitest/browser/context";

test("logs in and lands on the dashboard", async () => {
  await page.goto("/login");                       // action 1
  await page.fill("#email", "alice@example.com");  // action 2
  await page.fill("#password", "secret");          // action 3
  await page.click('button[type="submit"]');       // action 4
  await expect(page).toHaveURL("/dashboard");      // action 5 (fails in CI)
});

// ============================================
// PART 3: THE FAILURE THE TRACE EXPLAINS
// ============================================
// The assertion fails: the URL is still /login.
// The trace's DOM snapshot at action 5 shows the
// form with a visible validation error under #email:
// "Email is not registered."
// The trace's network tab shows the POST /api/login
// returned 401, which the UI rendered as that error.
// The bug is the test's fixture: alice@example.com
// does not exist in the CI database.

// ============================================
// PART 4: THE CONSOLE EVIDENCE
// ============================================
// The trace's console tab shows:
// [error] Failed to load resource: 401 (Unauthorized)
// [warning] React hydration completed after the
//           click handler attached — the first click
//           was lost. This is the second, real issue:
//           the test's click raced the hydration.

// ============================================
// PART 5: THE FIX GUIDED BY THE TRACE
// ============================================
test("logs in and lands on the dashboard", async () => {
  await page.goto("/login");
  // Wait for hydration before interacting —
  // the trace showed the click raced the hydration
  await expect(page.getByTestId("app-ready")).toBeVisible();
  await page.fill("#email", "bob@example.com");    // fixture that exists in CI
  await page.fill("#password", "secret");
  await page.click('button[type="submit"]');
  await expect(page).toHaveURL("/dashboard");
});

// ============================================
// PART 6: THE TRACE ON THE RETRY
// ============================================
// A flaky test's first attempt can fail before the
// trace is useful. The retry is the run to trace:
// test: { retry: 1 } records the second attempt,
// and the failed first attempt's trace is the one
// that shows the race the retry avoided.

The parts covered the config that records on failure, the test that produces the trace, the assertion failure the trace explains, the console evidence the trace preserves, the fix the trace guided, and the retry interaction that decides which attempt is traced.


Quick Reference

Trace Modes

ModeRecordsKeeps
"off"NoNothing
"on"Every testEvery trace
"retain-on-failure"Every testFailing tests only

Trace Contents

PanelShows
ActionsEach step, its timing, pass/fail
DOM snapshotSerialized DOM before/after each action
SourceTest lines around the selected action
NetworkRequests, responses, timing
ConsolePage logs and uncaught errors
MetadataBrowser, version, viewport, title

Viewer Commands

CommandPurpose
npx playwright show-trace <path>Open a trace file
npx playwright show-traceOpen the viewer, drop a file

Best Practices

✅ Do This:

// Record on failure in CI
contextOptions: { trace: "retain-on-failure" }                 // ✅

// Keep the trace artifact in CI
// upload test-results/ as the failure artifact              // ✅

// Read the console tab first for app errors
// the console explains the assertion's symptom              // ✅

// Compare the metadata's browser to local
// browser version differences explain CI-only failures     // ✅

// Record "on" only for a short local investigation
trace: "on"                                                    // ✅

❌ Don’t Do This:

// Record every test on every CI run
contextOptions: { trace: "on" }                                // ❌

// Ignore the network tab when the UI shows an error
// the error is usually a response the network tab has     // ❌

// Debug a CI failure without the trace artifact
// re-running to reproduce is expensive and unreliable     // ❌

// Blame the test before reading the console
// an app error is the root cause, not the assertion       // ❌

Common Pitfalls

PitfallWhy It HappensFix
No trace artifacttrace left at "off"Set retain-on-failure
Huge CI artifactstrace: "on" for every testRecord on failure only
Trace not foundOutput directory not uploadedUpload test-results/
Unreadable traceWrong file openedOpen trace.zip in the test’s folder
Missing networkTrace recorded without context optionsPass contextOptions to the provider
Timing bug invisibleOnly the final snapshot readToggle before/after and scrub the timeline

Real-World Examples

1. Trace on failure

contextOptions: { trace: "retain-on-failure" }

2. Trace always on

contextOptions: { trace: "on" } // local investigation only

3. Open a trace

npx playwright show-trace test-results/login/trace.zip

4. Upload the artifact

path: test-results/   # CI artifact for the failing run

5. Wait for hydration

await expect(page.getByTestId("app-ready")).toBeVisible();

6. Retry the flake

test: { retry: 1 } // trace the retry, not the first attempt

7. Read the console

// [error] 401 Unauthorized — the UI rendered it as a form error

8. Read the network

// POST /api/login → 401, matched to the failed assertion

9. Compare metadata

// trace metadata: chromium 128, viewport 1280x720

10. Toggle before/after

// the click's before and after snapshots are identical — no navigation

Visual

The Trace’s Four Aligned Panels

┌───────────────────────────────────────────────────────────┐
│  ACTIONS            DOM SNAPSHOT          SOURCE          │
│  ┌─────────────┐    ┌─────────────────┐   ┌────────────┐  │
│  │ 1 goto /login│──►│ <form>…</form>  │   │ page.goto  │  │
│  │ 2 fill email │──►│ <input value=…> │   │ fill(...)  │  │
│  │ 3 fill pass  │──►│ <input value=…> │   │ fill(...)  │  │
│  │ 4 click sub  │──►│ validation err  │   │ click(...) │  │
│  │ 5 expect URL │──►│ still /login ✗  │   │ expect(...)│  │
│  └─────────────┘    └─────────────────┘   └────────────┘  │
│                                                           │
│  NETWORK: POST /api/login → 401                           │
│  CONSOLE: [error] 401 Unauthorized                        │
│  METADATA: chromium 128 · 1280x720 · test title           │
└───────────────────────────────────────────────────────────┘

The Recording Modes

┌───────────────────────────────────────────────────────────┐
│  trace: "off"               trace: "on"                   │
│  ─────────────              ───────────                   │
│  no recording               record every test             │
│  no artifact                keep every trace              │
│  cheapest                   most expensive                │
│                                                           │
│  trace: "retain-on-failure"                               │
│  ─────────────────────────                                │
│  record every test                                        │
│  keep only the failing test's trace                       │
│  the production setting                                   │
└───────────────────────────────────────────────────────────┘

The Failure Debugging Workflow

┌───────────────────────────────────────────────────────────┐
│  CI failure                                               │
│      │                                                    │
│      ▼                                                    │
│  open trace.zip in the Trace Viewer                       │
│      │                                                    │
│      ▼                                                    │
│  select the failed action ──► read the DOM snapshot       │
│      │                                                    │
│      ├──► console tab ──► app error?                      │
│      ├──► network tab ──► wrong or missing response?      │
│      └──► metadata ──► browser differs from local?        │
│      │                                                    │
│      ▼                                                    │
│  step back one action ──► what set up the failing state?  │
└───────────────────────────────────────────────────────────┘

The Before/After Toggle

┌───────────────────────────────────────────────────────────┐
│  ACTION: click button[type="submit"]                      │
│                                                           │
│  BEFORE                        AFTER                      │
│  ┌───────────────────┐        ┌───────────────────┐       │
│  │ email: filled     │        │ email: filled     │       │
│  │ password: filled  │        │ validation error  │       │
│  │ button: enabled   │        │ button: enabled   │       │
│  │ url: /login       │        │ url: /login       │       │
│  └───────────────────┘        └───────────────────┘       │
│                                                           │
│  No navigation between before and after — the click's     │
│  effect was the validation error, not the expected route. │
└───────────────────────────────────────────────────────────┘

Summary

ItemValue
What it isRecorded timeline of a browser test
ProducerPlaywright provider in Vitest browser mode
Enabling optioncontextOptions.trace
Production mode"retain-on-failure"
Viewernpx playwright show-trace <path>
PanelsActions, DOM snapshot, source, network, console, metadata
Key affordanceBefore/after snapshots and timeline scrubbing
Artifact locationThe provider’s output directory

Key takeaways:

  • A trace is a timeline, not a screenshot. It records every action with the DOM snapshot before and after it, the network log, and the console, all aligned to the same clock, which is what makes asynchronous and timing failures debuggable after the fact.
  • The Playwright provider records it. Vitest’s browser mode passes contextOptions through to the browser context, and trace: "retain-on-failure" is the option that records every test but keeps only the failing test’s trace.
  • The Trace Viewer is the reading tool. npx playwright show-trace opens the file, and the viewer’s actions list, snapshots, and network and console tabs are the reading order for a failure.
  • The console tab is the first stop for an app error. An uncaught error or a failed request is usually the root cause, and the assertion failure is its symptom; the trace keeps both in the same artifact.
  • The metadata panel is the environment record. The browser version and viewport are the first comparison against local when a CI-only failure does not reproduce, and the trace preserves them without a separate log.
  • Record on failure only. Tracing every test on every CI run produces large artifacts for passing tests; "retain-on-failure" keeps the evidence exactly when it is needed.

Remember: A Playwright trace turns a browser test’s failure into a replayable timeline. Enable it through the Playwright provider’s contextOptions with trace: "retain-on-failure", keep the output directory as the CI artifact, and open the failing test’s trace.zip in the Trace Viewer. Read the actions for the failure’s position, the DOM snapshots for the state, the console and network for the root cause, and the metadata for the environment that produced it. The trace is the difference between a CI failure that is guessed at and one that is diagnosed.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!