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.
In this guide11 sections
- 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
- Choose Between Page and Locator Capture
- Select a Mode and Depth with a Decision Table
- Test the Boundary and Failure Matrix
- Debug Missing Nodes Systematically
- Govern the Evidence Contract in CI
- Frequently Asked Questions
- What values can the ariaSnapshot mode option use?
- How does ariaSnapshot depth limit the output?
- What depth should a Playwright ARIA snapshot use?
- Can AI-mode references be stored as selectors?
- How should depth and mode changes be reviewed in CI?
- 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
<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:
- Reach a deterministic application state and assert the named root is visible.
- Assert the deepest semantic node that the diagnostic must include.
- Capture default mode at the minimum depth needed for human review.
- Capture AI mode only when references or iframe context support a defined workflow.
- Check each artifact for expected scope and disallowed sensitive content.
- Attach runtime metadata and give each artifact a distinct purpose-based name.
- Fail the product test on behavior, then report capture-policy failures through their own gate.
Playwright 1.61.1 example: purpose-specific depth budgets
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
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 question | Root scope | Suggested mode | Depth approach | Why |
|---|---|---|---|---|
| Developer reviewing a role or name regression | Small named component | default | Omit depth or include the full component | Clean semantic output is easier to compare |
| CI diagnosing one nested form | Form or fieldset | default | Lowest value that includes the deepest asserted control | Limits unrelated text while preserving the failure path |
| Agent selecting an element on the current page | Small task region | ai | Allow reference-bearing wrappers around required controls | References support selection within current context |
| Agent working across embedded content | Parent region containing the iframe | ai | Budget for frame and descendant structure | AI mode includes iframe snapshots |
| Security-sensitive workflow with no approved model use | Narrow landmark | default | Minimize depth and retain locally | Avoids unnecessary references and wider frame context |
| Whole-page accessibility contract | Usually reconsider the scope | default | Prefer multiple component snapshots over a shallow page | Low 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.
| Boundary | Failure case | Observable evidence | Owner and response |
|---|---|---|---|
| Root locator | Named region is absent or duplicated | Locator assertion fails before capture | Product or fixture owner fixes semantics or state |
| Depth budget | Required save button falls below the limit | Direct button assertion passes, capture completeness check fails | Evidence owner raises depth or narrows root |
| Dynamic state | Snapshot records loading controls instead of the editor | State milestone is missing; tree shows progress content | Test owner waits for the owned condition |
| AI reference | Consumer reuses a reference after rerender | Selected element no longer matches captured semantics | Agent owner recaptures and validates current context |
| Frame context | Embedded support widget enters an AI snapshot unexpectedly | Artifact contains iframe nodes outside the task | Scope or privacy owner excludes the region |
| Sensitive text | Profile value appears in a deep descendant | Pre-export scan detects a disallowed field or pattern | Stop transfer, sanitize source data, review scope |
| Mode behavior | Missing target fails immediately in AI mode | Capture throws before expected default-mode wait | Test owner asserts readiness before AI capture |
| Cross-browser mapping | One project exposes a different accessibility shape | Project-specific artifact differs with behavior unchanged | Accessibility 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.
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.
- 01Official playwright.dev reference
playwright.dev
Primary documentation selected and verified for the claims in this guide.
- 02Official playwright.dev reference
playwright.dev
Primary documentation selected and verified for the claims in this guide.
- 03Official playwright.dev reference
playwright.dev
Primary documentation selected and verified for the claims in this guide.
- 04Official 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.
RELATED GUIDES
Continue the learning route
GUIDE 01
Playwright ARIA Snapshots for Testing Accessible Structure
Use Playwright ARIA snapshots to verify roles, names, states, and hierarchy with scoped templates, deliberate strictness, reviewable updates, and layered a11y tests.
GUIDE 02
Playwright Locators Guide: Find Elements Reliably
Playwright locators guide for stable UI tests with role selectors, filters, assertions, strict mode, debugging, and flaky selector fixes in CI.
GUIDE 03
Accessibility Testing Tools Compared
Compare accessibility testing tools: axe, Lighthouse, WAVE, screen readers, contrast checkers, and CI options so QA can pick a practical a11y stack.
GUIDE 04
Review AI-Generated Playwright Tests with an Evidence Checklist
Master review AI generated Playwright tests with practical examples, architecture decisions, failure analysis, CI guidance, metrics, and scenario-led interview answers.
GUIDE 05
Custom Playwright Matchers: Extend and Merge expect Safely
Create retry-aware Playwright custom matchers, merge expect modules without collisions, and preserve useful negation, timeout, and failure output.