PRACTICAL GUIDE / Playwright ariaSnapshot depth mode options

Control Playwright ARIA Snapshot Depth and Mode

Learn Playwright ariaSnapshot depth mode options with working code, failure cases, debugging steps, and CI evidence for reliable QA automation.

By The Testing AcademyUpdated July 18, 202617 min read
All field guides
In this guide11 sections
  1. Define the Capture Decision Before the Options
  2. Read the 1.61.1 API Exactly
  3. Observe How Depth Changes the Tree
  4. Implement Separate Human and AI Captures
  5. Choose Between Page and Locator Capture
  6. Select a Mode and Depth with a Decision Table
  7. Test the Boundary and Failure Matrix
  8. Debug Missing Nodes Systematically
  9. Govern the Evidence Contract in CI
  10. Frequently Asked Questions
  11. What values can the ariaSnapshot mode option use?
  12. How does ariaSnapshot depth limit the output?
  13. What depth should a Playwright ARIA snapshot use?
  14. Can AI-mode references be stored as selectors?
  15. How should depth and mode changes be reviewed in CI?
  16. Apply the Configuration in a QABattle Scenario

What you will learn

  • Define the Capture Decision Before the Options
  • Read the 1.61.1 API Exactly
  • Observe How Depth Changes the Tree
  • Implement Separate Human and AI Captures

Playwright ariaSnapshot depth mode options control how much accessible structure a capture contains and whether it is shaped for ordinary semantic inspection or AI consumption. Use a scoped locator, pick mode: 'default' or mode: 'ai' deliberately, and set a positive depth only after naming the required descendant. The failure boundary is silent omission beyond that depth.

A shorter snapshot can improve review speed, reduce private content, and keep an agent focused. It can also remove the only node that explains a failed interaction. A richer AI snapshot can include references and frame context, but that extra structure consumes attention and can expose data outside the immediate component. Good configuration begins with the decision, not a copied number.

Define the Capture Decision Before the Options

Write down who will read the snapshot and what they must decide. A developer investigating a changed heading hierarchy needs clean semantic YAML. A test-generation agent choosing a control may need references and iframe context. A CI attachment for a failed dialog assertion may need only the dialog and its first few descendant levels. These are different evidence contracts even when they start from the same page.

The captured root is the strongest size control. Scope to a form, dialog, navigation landmark, table, or named region before applying depth. If the locator starts at body, a low depth may retain headers and banners while cutting off the component under test. If it starts at the owned form, the same depth can include the labels, inputs, and actions that explain the failure.

Use the established Playwright locator guidance to select that root by role and accessible name. A CSS wrapper may be easy to identify today but disappear in a refactor without changing the user interface. A semantic root states why the subtree belongs in the artifact.

Keep the product requirement independent from the capture. An account form test should assert that a user can update a name and observe the saved value. Depth and mode decide what evidence accompanies a failure; they should not determine whether the update itself succeeded.

This guide owns output selection: how much hierarchy to serialize, where truncation occurs, and whether default or AI mode serves the consumer. The companion guide to ARIA snapshots with boxes owns geometry, coordinate interpretation, and spatial assertions. A depth decision should not silently become a layout baseline, and a boxed snapshot should not replace an explicit depth policy.

Read the 1.61.1 API Exactly

The official Playwright release notes list page.ariaSnapshot() plus the depth and mode options for locator snapshots. The installed 1.61.1 declarations expose the same options on both page.ariaSnapshot() and locator.ariaSnapshot(), along with boxes and timeout. Both methods resolve to a YAML string.

mode accepts "default" or "ai". Default mode produces the familiar accessibility-tree representation used for semantic inspection. AI mode adds references such as [ref=e7], includes nested iframe snapshots, and is optimized for a consumer that may need to point back to elements. On locator snapshots, AI mode does not wait for a missing match in the same way as default mode and throws when no element matches.

depth is a number. A positive value limits descendant serialization beneath the root. The root remains present, and nodes below the selected level are simply absent. The output does not add an ellipsis that tells a reader more content existed. Omit depth when the complete scoped tree is required. Prefer explicit positive values when limiting it; do not build policy around accidental or undocumented edge values.

The ARIA snapshot documentation describes the YAML as accessible structure, not DOM serialization. Default output can flatten unhelpful generic containers. AI output can preserve more of that context for references. As a result, depth: 3 is a traversal budget, not a promise to include three named interactive controls.

Observe How Depth Changes the Tree

Consider a settings surface with a named main landmark, form, group, and nested fields. The business contract concerns the textbox and save button, both several levels below the root.

Fixture: nested account settings

HTML
<main aria-label="Account settings">
  <form aria-label="Profile details">
    <fieldset>
      <legend>Identity</legend>
      <label>
        Display name
        <input name="displayName" value="Asha Rao">
      </label>
      <button type="submit">Save profile</button>
    </fieldset>
  </form>
</main>

A default snapshot at depth one may stop after the form. Depth two may reach the group but still omit the textbox and button. Increasing the depth reveals those descendants. AI mode may retain an extra generic wrapper around label text or another contextual node, so its useful control can appear at a deeper level than in default output.

This has two testing consequences. First, validate the chosen depth against representative fixtures rather than counting HTML tags. Accessibility-tree construction can flatten or introduce nodes based on semantics. Second, add a deterministic assertion for the deepest required element. If a component library adds a wrapper and the capture becomes too shallow, that assertion identifies a capture regression instead of allowing incomplete evidence to pass unnoticed.

The core Playwright ARIA snapshots article explains roles, names, states, text, and hierarchy in the default representation. Learn that semantic shape before deciding which parts an AI-oriented mode should retain.

Implement Separate Human and AI Captures

One test can create different evidence for different readers without making both permanent. The human attachment can remain concise and unreferenced. The AI attachment can be generated only on failure, only in a controlled evaluation job, or only after a policy check permits its content.

Follow this sequence:

  1. Reach a deterministic application state and assert the named root is visible.
  2. Assert the deepest semantic node that the diagnostic must include.
  3. Capture default mode at the minimum depth needed for human review.
  4. Capture AI mode only when references or iframe context support a defined workflow.
  5. Check each artifact for expected scope and disallowed sensitive content.
  6. Attach runtime metadata and give each artifact a distinct purpose-based name.
  7. Fail the product test on behavior, then report capture-policy failures through their own gate.

Playwright 1.61.1 example: purpose-specific depth budgets

TypeScript
import { test, expect } from '@playwright/test';

test('profile editor exposes useful failure context', async ({ page }, testInfo) => {
  await page.goto('/settings/profile');

  const settings = page.getByRole('main', { name: 'Account settings' });
  const save = settings.getByRole('button', { name: 'Save profile' });

  await expect(settings).toBeVisible();
  await expect(save).toBeEnabled();

  const reviewSnapshot = await settings.ariaSnapshot({
    mode: 'default',
    depth: 3,
  });

  await testInfo.attach('profile-semantics', {
    body: reviewSnapshot,
    contentType: 'text/yaml',
  });

  if (process.env.CAPTURE_AI_CONTEXT === '1') {
    const agentSnapshot = await settings.ariaSnapshot({
      mode: 'ai',
      depth: 5,
      timeout: 3_000,
    });

    await testInfo.attach('profile-agent-context', {
      body: agentSnapshot,
      contentType: 'text/yaml',
    });
  }
});

The different depth values are not a rule to copy. They document that AI mode needs room for extra contextual nodes in this fixture. A repository should derive its values from owned components and check them with small contract tests. Environment-controlled capture is also not a privacy control by itself; the branch still needs data classification and redaction before an external service receives the text.

If several suites need this pattern, a thin helper can standardize attachment names and policy checks. The custom Playwright matcher guide is useful for error-message design, though a capture helper does not need to pretend to be an assertion. Keep collection and acceptance visibly separate.

Choose Between Page and Locator Capture

page.ariaSnapshot() and locator.ariaSnapshot() accept the same capture options in Playwright 1.61.1, but they express different ownership. Page capture is equivalent to starting from the document body and is useful when the whole current page is the diagnostic subject. Locator capture starts from the element resolved by that locator, which makes component ownership, privacy review, and depth selection much clearer.

A page-level depth limit can be deceptive. At depth two, the output may include top navigation and a main landmark but omit a deeply nested editor, even though that editor caused the failure. Raising the depth pulls more content from every branch. A locator rooted at the named editor spends the same traversal budget inside the relevant component. That is why narrowing scope should be the first response to missing evidence, before increasing the numeric limit.

Page capture also broadens the data boundary. Account menus, support widgets, notification text, and embedded payment or analytics frames may enter an AI-oriented snapshot. Even when the test uses synthetic values, unrelated feature flags or customer-like fixtures can create retention concerns. Treat whole-page AI capture as a separately approved use case, not a convenient fallback when a component locator is difficult to write.

Locator capture has a readiness boundary that deserves an explicit assertion. Default mode can wait for the target within the configured timeout, while AI mode is designed to fail when no target matches instead of waiting in the same way. Neither behavior proves that the subtree reached the intended application state. A matched form can still contain a spinner, stale validation error, or disabled action. Use a locator assertion for the state milestone before collecting either mode.

The timeout option limits the capture operation. It should not become the test's state model. Increasing it may help a legitimately slow target resolve in default mode, but it does not tell Playwright which business transition is complete. A named status, enabled control, response-backed result, or stable heading gives the test a meaningful readiness condition and a better failure message.

Capture helper: make scope and consumer explicit

TypeScript
import type { Locator, TestInfo } from '@playwright/test';

type SnapshotProfile = {
  audience: 'reviewer' | 'agent';
  depth?: number;
};

async function attachAriaContext(
  root: Locator,
  profile: SnapshotProfile,
  testInfo: TestInfo,
) {
  const body = await root.ariaSnapshot({
    mode: profile.audience === 'agent' ? 'ai' : 'default',
    depth: profile.depth,
    timeout: 3_000,
  });

  await testInfo.attach(`aria-${profile.audience}`, {
    body,
    contentType: 'text/yaml',
  });
}

Requiring a Locator prevents casual whole-page export through this helper. A separate, visibly named function can own approved page-level capture if the repository needs it. The type does not enforce privacy, but it makes the broad operation harder to introduce accidentally and gives code review a clear policy boundary.

Frame content needs the same discipline. AI mode can include iframe snapshots under the target, which is valuable when the task genuinely crosses an embedded editor or payment field. It is unnecessary when the frame is a support launcher outside the scenario. Root beneath an owned frame when possible, or exclude the parent region from model-facing evidence. Do not assume a shallow depth always removes private frame data, because the frame can sit near the root.

Finally, pair capture scope with interaction scope. If the executable locator acts inside one component while the evidence covers the full page, a model can cite an unrelated but similarly named control. The visual accessibility scenario guide reinforces the value of naming the precise user surface, and the locator guide shows how role, name, filters, and frame locators can keep that surface explicit.

Select a Mode and Depth with a Decision Table

The right combination follows the consumer and boundary. This table provides starting choices, not global defaults.

Consumer and questionRoot scopeSuggested modeDepth approachWhy
Developer reviewing a role or name regressionSmall named componentdefaultOmit depth or include the full componentClean semantic output is easier to compare
CI diagnosing one nested formForm or fieldsetdefaultLowest value that includes the deepest asserted controlLimits unrelated text while preserving the failure path
Agent selecting an element on the current pageSmall task regionaiAllow reference-bearing wrappers around required controlsReferences support selection within current context
Agent working across embedded contentParent region containing the iframeaiBudget for frame and descendant structureAI mode includes iframe snapshots
Security-sensitive workflow with no approved model useNarrow landmarkdefaultMinimize depth and retain locallyAvoids unnecessary references and wider frame context
Whole-page accessibility contractUsually reconsider the scopedefaultPrefer multiple component snapshots over a shallow pageLow page depth can omit the relevant application area

Do not use AI mode merely because a test was generated by AI. If the test only needs a readable semantic diff, default mode is often the clearer artifact. Conversely, do not strip references from an agent workflow and then ask the model to infer which of several identical controls it meant.

The guide to reviewing AI-generated Playwright tests can help reviewers ask whether the selected mode adds verifiable evidence or only more tokens. Artifact size, private content, and model cost are operational concerns, but none justifies cutting off the control that owns the failure.

Test the Boundary and Failure Matrix

A depth/mode suite needs cases that prove collection fails visibly. The matrix below separates application, capture, and consumer defects.

BoundaryFailure caseObservable evidenceOwner and response
Root locatorNamed region is absent or duplicatedLocator assertion fails before captureProduct or fixture owner fixes semantics or state
Depth budgetRequired save button falls below the limitDirect button assertion passes, capture completeness check failsEvidence owner raises depth or narrows root
Dynamic stateSnapshot records loading controls instead of the editorState milestone is missing; tree shows progress contentTest owner waits for the owned condition
AI referenceConsumer reuses a reference after rerenderSelected element no longer matches captured semanticsAgent owner recaptures and validates current context
Frame contextEmbedded support widget enters an AI snapshot unexpectedlyArtifact contains iframe nodes outside the taskScope or privacy owner excludes the region
Sensitive textProfile value appears in a deep descendantPre-export scan detects a disallowed field or patternStop transfer, sanitize source data, review scope
Mode behaviorMissing target fails immediately in AI modeCapture throws before expected default-mode waitTest owner asserts readiness before AI capture
Cross-browser mappingOne project exposes a different accessibility shapeProject-specific artifact differs with behavior unchangedAccessibility owner investigates before changing policy

Include ordinary, shallow, nested, dynamic, framed, and sensitive fixtures in the collector's own tests. Product scenarios do not need every permutation. This division prevents all application tests from carrying evidence-framework complexity while still proving the helper works at its limits.

Use accessibility testing tools alongside snapshots when the question is standards violations rather than a known structural contract. Depth can hide a violation-bearing descendant from the artifact; it does not change whether the underlying page has the issue.

Debug Missing Nodes Systematically

When a node is absent, begin with the live locator. Can getByRole find it by the expected name and state? If not, investigate rendering, accessible naming, hidden state, or frame ownership. If the locator succeeds, capture without a depth limit at the same scoped root. This distinguishes a semantic absence from intentional truncation.

Next compare default and AI output. A generic wrapper present in AI mode may consume another traversal level. A frame subtree may appear only in the AI-oriented capture. Record the first depth at which the required node appears, then decide whether narrowing the root is cleaner than increasing the budget. A smaller root often reduces both artifact size and accidental exposure.

Do not repair the symptom by searching the YAML string for raw DOM text. The missing accessible node may signal a real label or role defect. Keyboard navigation testing adds the behavioral layer when a node exists in the tree but cannot be reached or activated. A semantic capture and an operability check answer different questions.

If CI alone differs, compare Playwright and browser versions, project configuration, locale, feature flags, test data, and readiness markers. For accompanying pixel changes, use the workflow for debugging visual snapshot CI diffs. Do not raise depth until an environment mismatch has been ruled out.

Finally, inspect errors without overwriting the original failure. Playwright 1.60 introduced TestInfoError.errorContext, described in the official TestInfoError reference, for additional matcher context such as an ARIA snapshot. Keep that generated context beside any purpose-specific capture; one records the failing receiver, while the other records the configured diagnostic scope.

Govern the Evidence Contract in CI

Store the mode, depth, root locator intent, and consumer in a short policy record near the helper or test. A reviewer should be able to answer why the artifact exists, which descendants must appear, whether it may leave CI, and how long it is retained. An unexplained depth: 8 is not governance, even if it currently captures everything.

Add a completeness canary to the evidence layer. For each approved component shape, verify that the chosen options include one deepest required role and exclude one known out-of-scope region. This catches wrapper changes, accidental page-level capture, and overly aggressive truncation without baselining the entire YAML string.

Report capture failures separately from product failures. A missing profile save button is a product blocker. A failed optional AI attachment may be an evidence-pipeline incident while the deterministic product test still reports its own result. If policy requires the diagnostic for high-risk changes, CI can block on evidence completeness with a different label and owner.

Avoid automatic option expansion. A helper should not keep raising depth until it finds a named string, because that can pull in private descendants or unrelated frames. Make the change in code, show the before-and-after scope, and review it. The AI test evidence checklist is a practical review companion for model-facing changes.

Sample artifact size and sensitive-data findings over time. A sudden increase can reveal a scope regression before storage cost becomes the obvious symptom. Pin Playwright 1.61.1 and its browsers for the initial baseline, then rerun collector contract tests during upgrades. Review semantic differences rather than assuming the same numeric depth means the same information across versions.

Frequently Asked Questions

What values can the ariaSnapshot mode option use?

In Playwright 1.61.1, mode accepts default or ai. Default produces the conventional semantic YAML view. AI mode adds element references, preserves context intended for AI consumers, includes iframe snapshots, and changes missing-target waiting behavior. The choice affects capture output, not the meaning of your separate product assertions.

How does ariaSnapshot depth limit the output?

A positive depth limits how many descendant levels are serialized below the captured root. Nodes beyond the limit are omitted without an ellipsis or truncation warning. Because AI mode can preserve generic containers that default output flattens, the same number may expose different useful descendants in the two modes.

What depth should a Playwright ARIA snapshot use?

There is no universal number. Start at the smallest stable landmark, then choose the lowest positive depth that includes the control, state, or relationship the consumer needs. Add a direct assertion for that required node so a later wrapper does not silently push it beyond the capture budget.

Can AI-mode references be stored as selectors?

No. References such as [ref=e7] identify elements within generated AI context; they are not durable application IDs or authored locators. Do not persist them across navigation or rerendering. Recreate the snapshot for the current state, validate the referenced element's semantics, and keep Playwright locators as the executable test interface.

How should depth and mode changes be reviewed in CI?

Review an option change as an evidence-contract change. Show which nodes appear or disappear, whether frame content enters scope, how artifact size and sensitive text change, and which consumer needs the new form. Product gates should fail on owned behavior, while capture completeness and privacy receive separate policy checks.

Apply the Configuration in a QABattle Scenario

Begin with one nested component and two consumers. Capture a complete default view for a developer, then create the smallest AI view that still includes the actionable descendant. Deliberately lower the depth until the control disappears. That failure teaches the team more about the boundary than copying a generous value into every test.

Use a scenario from QABattle battles to practice the review. Name the root, deepest required node, mode, depth, and data policy before collecting anything. Then prove the interaction through a locator assertion and treat the snapshot as accountable evidence. The result is a capture configuration that can explain a failure without quietly defining what passing means.

// LIVE COURSE / THE TESTING ACADEMY

Playwright Automation Mastery

Go beyond Selenium. Master Playwright with JS/TS in 90 days.

From the instructor behind this guide.

Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.

Code PROMODE / 10% offJoin the batch

The Testing Academy editorial desk

Practical QA guidance built around test evidence, production tradeoffs, and interview-ready explanations.

Published July 18, 2026 / Reviewed July 18, 2026

PRIMARY REFERENCES

Verify the details at the source

QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.

  1. 01
    Official playwright.dev reference

    playwright.dev

    Primary documentation selected and verified for the claims in this guide.

  2. 02
    Official playwright.dev reference

    playwright.dev

    Primary documentation selected and verified for the claims in this guide.

  3. 03
    Official playwright.dev reference

    playwright.dev

    Primary documentation selected and verified for the claims in this guide.

  4. 04
    Official playwright.dev reference

    playwright.dev

    Primary documentation selected and verified for the claims in this guide.

FAQ / QUICK ANSWERS

Questions testers ask

What values can the ariaSnapshot mode option use?

In Playwright 1.61.1, mode accepts default or ai. Default produces the conventional semantic YAML view. AI mode adds element references, preserves context intended for AI consumers, includes iframe snapshots, and changes missing-target waiting behavior. The choice affects capture output, not the meaning of your separate product assertions.

How does ariaSnapshot depth limit the output?

A positive depth limits how many descendant levels are serialized below the captured root. Nodes beyond the limit are omitted without an ellipsis or truncation warning. Because AI mode can preserve generic containers that default output flattens, the same number may expose different useful descendants in the two modes.

What depth should a Playwright ARIA snapshot use?

There is no universal number. Start at the smallest stable landmark, then choose the lowest positive depth that includes the control, state, or relationship the consumer needs. Add a direct assertion for that required node so a later wrapper does not silently push it beyond the capture budget.

Can AI-mode references be stored as selectors?

No. References such as [ref=e7] identify elements within generated AI context; they are not durable application IDs or authored locators. Do not persist them across navigation or rerendering. Recreate the snapshot for the current state, validate the referenced element's semantics, and keep Playwright locators as the executable test interface.

How should depth and mode changes be reviewed in CI?

Review an option change as an evidence-contract change. Show which nodes appear or disappear, whether frame content enters scope, how artifact size and sensitive text change, and which consumer needs the new form. Product gates should fail on owned behavior, while capture completeness and privacy receive separate policy checks.