#The Trace Viewer
AddedA test that fails on your laptop is easy: run it again with the browser open and watch. A test that failed on CI, once, an hour ago is the hard case, and it's the normal case. You can't watch it any more. What you need is a recording of everything that happened, detailed enough to answer "what did the page look like when the click happened?" without running anything again.
That's a trace: a trace.zip that Playwright writes while a test runs, holding every action with its timing, a DOM snapshot before, during and after each action (real HTML you can inspect, not a picture), a screencast, every network request and response, console messages, errors and the test's source. The Trace Viewer opens it as an interactive timeline.
The mental model: an aeroplane's flight recorder. You don't watch it during a normal flight; it costs little to keep running; and when something goes wrong, it's the only witness. So the usual setting records traces only when something goes wrong: trace: "on-first-retry" (record when a failed test is retried) or trace: "retain-on-failure" (record every test, keep the trace only if it failed).
Here a test fails, and the trace explains why. The test author believed the Wireless Mouse was the first product:
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: {
baseURL: "https://rohit-playwright.pages.dev",
trace: "retain-on-failure", // record every test, keep the trace only when it fails
},
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});import { test, expect, type Page } from "@playwright/test";
async function signIn(page: Page) {
await page.goto("/practice/");
await page.getByLabel("Username").fill("rohit");
await page.getByLabel("Password").fill("playwright");
await page.getByRole("button", { name: "Sign in" }).click();
}
test("signing in shows the products", async ({ page }) => {
await signIn(page);
await expect(page.getByRole("listitem")).toHaveCount(8);
});
test("adding the mouse names it in the message", async ({ page }) => {
await signIn(page);
await page.getByRole("button", { name: "Add to cart" }).first().click(); // "the mouse is first" (it isn't)
await expect(page.getByRole("status").filter({ hasText: "Added" })).toHaveText("Added Wireless Mouse to your cart", { timeout: 2000 });
});Running 2 tests using 1 worker
✓ 1 [chromium] › tests/toast.spec.ts:10:1 › signing in shows the products (1.5s)
✘ 2 [chromium] › tests/toast.spec.ts:15:1 › adding the mouse names it in the message (3.5s)
1) [chromium] › tests/toast.spec.ts:15:1 › adding the mouse names it in the message ──────────────
Error: expect(locator).toHaveText(expected) failed
Locator: getByRole('status').filter({ hasText: 'Added' })
Expected: "Added Wireless Mouse to your cart"
Received: "Added Mechanical Keyboard to your cart"
Timeout: 2000ms
Call log:
- Expect "toHaveText" getByRole('status').filter({ hasText: 'Added' }) with timeout 2000ms
- waiting for getByRole('status').filter({ hasText: 'Added' })
21 × locator resolved to <div class="toast" role="status" data-toast="">Added Mechanical Keyboard to your cart</div>
- unexpected value "Added Mechanical Keyboard to your cart"
16 | await signIn(page);
17 | await page.getByRole("button", { name: "Add to cart" }).first().click(); // "the mouse is first" (it isn't)
> 18 | await expect(page.getByRole("status").filter({ hasText: "Added" })).toHaveText("Added Wireless Mouse to your cart", { timeout: 2000 });
| ^
19 | });
20 |
at <project>/tests/toast.spec.ts:18:71
Error Context: test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/error-context.md
attachment #2: trace (application/zip) ─────────────────────────────────────────────────────────
test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/trace.zip
Usage:
npx playwright show-trace test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/trace.zip
────────────────────────────────────────────────────────────────────────────────────────────────
1 failed
[chromium] › tests/toast.spec.ts:15:1 › adding the mouse names it in the message ───────────────
1 passed (5.5s)// Prints every file under the given folders, sorted, so the page can show what a run really wrote.
import { readdirSync } from "node:fs";
import { join } from "node:path";
const walk = (d) => readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)]));
for (const dir of process.argv.slice(2)) for (const f of walk(dir).sort()) console.log(f);test-results/.last-run.json
test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/error-context.md
test-results/toast-adding-the-mouse-names-it-in-the-message-chromium/trace.zip- Both tests ran with tracing on. The passing test's trace was thrown away when it passed (that's what
retain-on-failuremeans), sotest-results/holds a folder only for the failing test: itstrace.zipand anerror-context.md. - The failure itself is already informative: the message said "Added Mechanical Keyboard to your cart", not the mouse. The output also prints the exact command to open the recording:
npx playwright show-trace test-results/…/trace.zip. - In the Trace Viewer (a window, so it wasn't run for this page; this is from the docs) you'd click the Click action in the list on the left and see three DOM snapshots: Before, Action (marking the point where the click landed) and After. The click point is on the first card, the Mechanical Keyboard. The bug is in the test, not the shop:
.first()assumed an order nobody promised. - The fix is a locator that says what the test means:
page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" })(Chapter 4). The trace didn't just say that the test failed; it showed what the test actually did, which is the question you can't answer from the error alone.
Since 1.59, npx playwright trace reads a trace from the command line: trace open <file>, then actions, action <id>, requests, console, errors, snapshot, screenshot, attachments, and close. The release notes say it was added so coding agents can inspect failing tests, but it's just as handy over SSH or in a CI log. This little script runs it on the failing test's trace and hides the timings, which change every run:
// Reads a trace with `npx playwright trace` and prints the action list and the errors, with timings hidden.
import { execFileSync } from "node:child_process";
const trace = (...args) => execFileSync("npx", ["playwright", "trace", ...args], { encoding: "utf8" });
const hideTimes = (s) => s.replace(/\d+:\d\d\.\d{3}/g, "…").replace(/\b\d+(\.\d+)?m?s\b/g, "…");
const summary = trace("open", process.argv[2]);
console.log(summary.split("\n").filter((l) => !/Duration|Start time/.test(l)).join("\n"));
console.log(hideTimes(trace("actions")));
console.log(trace("errors"));
trace("close"); Browser: unknown
Platform: darwin
Playwright: 1.65.1
Title: toast.spec.ts:15 › adding the mouse names it in the message
Viewport: default
Actions: 26
Pages: 1
Network: 7 requests
Errors: 1
Attachments: 1
Console: 0 messages
# Time Action Duration
──── ───────── ─────────────────────────────────────────────────────── ────────
1. … Before Hooks …
2. … Fixture "context" …
3. … Create context …
4. … Fixture "page" …
5. … Create page …
6. … Navigate …
/practice/
7. … Fill "rohit" …
getByLabel('Username')
8. … Fill "playwright" …
getByLabel('Password')
9. … Click …
getByRole('button', { name: 'Sign in' })
10. … Click …
getByRole('button', { name: 'Add to cart' }).first()
11. … Expect "toHaveText" … ✗
getByRole('status').filter({ hasText: 'Added' })
12. … After Hooks …
13. … Fixture "page" …
14. … Fixture "context" …
15. … Close context …
16. … Attach "error-context" …
17. … Worker Cleanup …
18. … Fixture "browser" …
✗ Error
at toast.spec.ts:18:71
Error: expect(locator).toHaveText(expected) failed
Locator: getByRole('status').filter({ hasText: 'Added' })
Expected: "Added Wireless Mouse to your cart"
Received: "Added Mechanical Keyboard to your cart"
Timeout: 2000ms
Call log:
- Expect "toHaveText" getByRole('status').filter({ hasText: 'Added' }) with timeout 2000ms
- waiting for getByRole('status').filter({ hasText: 'Added' })
21 × locator resolved to <div class="toast" role="status" data-toast="">Added Mechanical Keyboard to your cart</div>
- unexpected value "Added Mechanical Keyboard to your cart"trace openunpacks the zip and prints a summary: the Playwright version, the test's title, how many actions, network requests and errors were recorded. (The "Browser: unknown" line is what 1.65.1 really printed for this trace.)trace actionslists every step in order, including the fixtures Playwright set up (context,page) and tore down. Each Playwright call is one line with its locator: the Click ongetByRole('button', { name: 'Add to cart' }).first(), then the Expect "toHaveText" marked ✗.trace errorsprints the failing assertion, with its location in the source and its call log: expected "Added Wireless Mouse to your cart", received the keyboard message.- From here you could run
npx playwright trace snapshot <action-id>to inspect the DOM at that step, ortrace requeststo see the network. The GUI is nicer for humans; the CLI is what you'd script, or hand to an AI agent (Chapter 13).
The values, from the 1.65 CLI help and the option's documentation in the installed types:
trace: | Records | Use it for |
|---|---|---|
"off" | nothing | the default |
"on" | every test | debugging locally; too heavy for a whole CI suite |
"retain-on-failure" | every run, keeps the runs that failed (even when a later retry passes) | CI, with or without retries |
"on-first-retry" | the first retry of a failed test | CI with retries (the generator's default) |
"on-all-retries" | every retry | chasing a flake that fails several times |
"retain-on-first-failure" | only the first run of each test (not retries), kept if it failed | CI with retries, when the first failure is the one you want |
"retain-on-failure-and-retries" (1.59+) | every run, keeps failed runs and every retry | comparing a failing attempt with the passing retry of a flaky test |
Where to open a trace: npx playwright show-trace path/to/trace.zip (a local window), the HTML report (each failed test has a trace link), or trace.playwright.dev, which loads the file entirely in your browser (the docs say no data is sent anywhere). Traces contain everything the page showed and sent, including tokens and personal data in requests, so treat CI trace artifacts as sensitive.