Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 35 ยท Debugging and Reports

Debugging Failing Tests

Find out why a browser test fails: Cypress time travel and cy.pause, Playwright UI mode, inspector and codegen, screenshots, and how to read errors.

Every test suite fails sometimes, and the skill that separates a calm team from a frustrated one is how fast they find out why. A browser test failure has several possible causes: the app is broken, the test is wrong, the data was not what you assumed, or the timing was unlucky. Cypress and Playwright both ship strong tools for answering that question. This lesson tours them and gives you a method for reading an error.

These tools need a real browser and a desktop window, so they cannot run here. The commands are shown read-only. The runnable examples are stand-ins: a step recorder that keeps a snapshot before and after every command (the idea behind "time travel"), and a step-through debugger that pauses a test at a chosen step.

Start with the error message

Before reaching for any tool, read the failure. Good messages tell you three things: what the test was doing, what it expected and what it found.

TEXT
// Cypress (read-only, typical shape)
AssertionError: Timed out retrying after 4000ms:
  expected '<h1>' to contain 'Dashboard'

// Playwright (read-only, typical shape)
Error: expect(locator).toHaveText(expected)
Locator: getByRole('heading', { level: 1 })
Expected string: "Dashboard"
Received string: "Sign in"
Call log:
  - waiting for getByRole('heading', { level: 1 })

Both say the same thing: the page showed "Sign in" when the test expected "Dashboard". That points at login, not at the dashboard. Ask in order:

  1. Which line failed? The stack trace and the highlighted code in the report tell you.
  2. Did the element exist at all? "Not found" is a different problem from "found, but with other text".
  3. What did the page look like at that moment? A screenshot answers this faster than any log.
  4. Does it fail every time? If not, you are dealing with flakiness (Finding and Fixing Flaky Tests).

Debugging in Cypress

The Cypress app (opened with npx cypress open) has the best-known debugging feature of either tool: time travel. The left side of the window lists every command in the command log. Hover over a command and the page on the right shows the DOM as it was at that moment; click it to pin that snapshot and inspect the elements with your browser's developer tools. For click and type, the page also highlights where the action landed.

Other tools in the same window:

  • cy.pause() stops the test at that point so you can step command by command.
  • .debug() logs the current subject to the browser console and sets a breakpoint when developer tools are open: cy.get('.row').debug().
  • debugger inside .then() pauses in the browser's debugger (placing it directly in the test body runs it too early because of the command queue; see How Cypress Commands Really Work).
  • cy.log('message') adds a line to the command log.
  • Selector Playground helps you choose a selector by clicking an element.
  • Screenshots and video. cypress run takes a screenshot automatically when a test fails. Videos are off by default in current versions (video: true turns them on). Take one yourself with cy.screenshot('after-login').
JavaScript
// Cypress (read-only)
it('shows the dashboard', () => {
  cy.visit('/login')
  cy.get('[data-cy=email]').type('[email protected]')
  cy.pause()                       // step from here in the interactive runner
  cy.contains('button', 'Sign in').click()
  cy.get('h1').debug()             // log the element, break if DevTools is open
  cy.get('h1').then(($h1) => {
    debugger                       // runs when the h1 exists
  })
  cy.screenshot('dashboard')
})

Debugging in Playwright

Playwright offers several complementary tools, all started from the command line:

Tool Command Best for
UI mode npx playwright test --ui Watching tests, time travel through a timeline, filtering, rerunning on file save
Inspector npx playwright test --debug Stepping through actions one by one with a live browser
Headed run npx playwright test --headed Simply watching the browser
Trace viewer npx playwright show-trace trace.zip Studying a run after the fact; see the next lesson
Codegen npx playwright codegen https://example.com Recording clicks to discover locators

You can also pause from code with await page.pause(), which opens the inspector at that line in a headed run:

TypeScript
// Playwright (read-only)
test('shows the dashboard', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('[email protected]');
  await page.pause();                          // inspector opens here
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page.getByRole('heading', { level: 1 })).toHaveText('Dashboard');
});

UI mode and the trace viewer both show a timeline, with a snapshot of the page before and after each action plus the network calls and console messages. The inspector can also highlight which element a locator matches, which is the quickest way to see why a locator is wrong or matches several elements. Codegen is excellent for learning locators, but treat its output as a draft: rename things, add your own assertions and replace fragile selectors, as described in Writing Selectors That Do Not Break.

In VS Code, the Playwright extension lets you set a breakpoint and click "Debug test" with a live browser. Because Playwright tests are plain async functions, ordinary console.log also works and prints in your terminal.

A step recorder, the idea behind time travel

Why can these tools show the page "as it was" three commands ago? Because they record a snapshot around every step. The stand-in below does the same with a fake page. Each command is wrapped so that the runner stores the state before and after it, along with the outcome. When a step fails, you can look back at the last good state.

JS A step recorder with snapshots

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The log points at step 4 as the failure, but the cause sits in step 3: clicking the button produced the error "Password is required". This is the same detective work you do in the Cypress command log, only here the history is a plain array. That "the failing line is rarely the guilty line" pattern is the most important debugging lesson of all.

Stepping through a test

Pausing is the second basic technique. The stand-in below writes a test as a generator: each yield is one step, and the runner decides when to continue. It mimics cy.pause() and page.pause(), which stop the test so you can look around and then resume.

JS Pausing and stepping a test

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pausing in a real runner works the same way in spirit: execution stops, the browser stays open and you can poke at the live page with developer tools before continuing.

flowchart TD
  F["Test fails"] --> R["Read the error:<br/>what, expected, found"]
  R --> S["Look at a screenshot<br/>or snapshot"]
  S --> Q{"Element missing<br/>or wrong value?"}
  Q -->|"Missing"| L["Check locator<br/>and timing"]
  Q -->|"Wrong value"| A["Check app state<br/>and test data"]
  L --> P["Pause, step, retry"]
  A --> P

A repeatable path from a red test to a cause.

Habits that save time

  • Run one test. Use it.only or test.only while debugging (and remove it afterwards), or pass a file or --grep pattern.
  • Make it fail on purpose. After fixing, change an expected value and confirm the test fails; a test that cannot fail proves nothing.
  • Debug the smallest failing case. Delete steps until the failure stops, then restore the last one.
  • Do not add waits as a first reaction. A sleep hides the symptom. Find the condition you are really waiting for (Auto-Waiting in Playwright).
  • Keep evidence in CI. Screenshots, videos and traces from failed runs turn "cannot reproduce" into a solved problem, which is the subject of Traces, Videos and Reports.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Cypress time travel let you do?

    The command log stores DOM snapshots, so hovering or clicking a command shows the page state around it.
  2. 2. Which command opens Playwright's inspector for a test run?

    --debug runs headed and opens the inspector so you can step through actions. page.pause() does a similar thing from inside a test.
  3. 3. A Cypress test fails on the line that asserts the dashboard heading, but the screenshot shows the login page with an error. Where is the real problem likely to be?

    The failing line is where the symptom appeared. The cause is often earlier, which snapshots and screenshots help you see.
  4. 4. Why is adding a fixed sleep a poor first fix for a failing test?

    Waiting for a specific, observable condition is both faster and more reliable than waiting for an arbitrary time.
  5. 5. What is the best way to treat the output of Playwright codegen?

    Codegen is great for discovering locators, but a draft needs meaningful names, assertions and sturdy selectors.

Summary

  • Read the error first: what the test did, what it expected and what it found.
  • The failing line is where the symptom showed up; the cause is often an earlier step.
  • Cypress offers time travel, cy.pause(), .debug() and automatic screenshots on failure in cypress run.
  • Playwright offers UI mode, the inspector (--debug, page.pause()), headed runs, codegen and the trace viewer.
  • Run a single test, shrink the failing case and avoid sleeps as a first fix.
  • Capture evidence in CI so failures can be diagnosed later.

Next: Traces, Videos and Reports