Testing accessibility
Learn web components accessibility testing: run axe-core across shadow DOM, read Chrome's accessibility tree, and check keyboards and screen readers by hand.
- 01Run axe on a componentCheck open shadow roots with axe-core, read its violations and review items, and test one part with
fromShadowDom. - 02Read the accessibility treeFind each part's role, name, and state in Chrome DevTools, and tell which step of the name rules gave the name.
- 03Test what tools can'tWork through a checklist with the keyboard, zoom, forced colors, reduced motion, right to left, and a screen reader.
How do you test a web component for accessibility?
The tea kit is ready for Leaf and Kettle's new menu. In this stage, Ravi gave it roles and names, keys that work, a checkout dialog, colors that pass, and a right-to-left layout. The menu goes live next week.
Leela orders with a screen reader. Mariam reads the menu in Arabic. Ravi wants to know that it all works for them. He also wants to know it still works after his next change. How does he test that?
Test a web component in three layers. An automated checker, like axe-core, reads open shadow roots and reports the rule breaks it is sure of. Chrome's accessibility tree shows each part's role, name, and state. And a person works through a short checklist with the keyboard, zoom, and a screen reader.
Ravi starts with the quickest layer. axe-core is an open-source checker made by Deque. The Chrome DevTools docs say it's the engine behind the Lighthouse panel's accessibility checks. Here it checks the tea card, as lesson 15.2 left it:
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-card name="Sencha" price="4"></tea-card><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> import "./tea-kit/index.js"; const results = await axe.run("tea-card"); console.log("Violations:", results.violations.length); console.log("Needs review:", results.incomplete.length); console.log("Rules passed:", results.passes.length);</script>- Lines 1 and 2 are the kit's tokens and the card.
- Line 3 loads axe-core from jsDelivr, a site that serves npm packages. The version, 4.14.1, is in the address, so every run uses the same release. The script makes one global,
axe. - Line 6 checks the card, and everything inside its shadow root.
axe.run()gives back a promise of the results. - Lines 7 to 9 print how long three lists in the results are.
It prints Violations: 0, Needs review: 1, and Rules passed: 13. axe's API docs explain the three lists:
- Violations are rules that failed. axe only puts a rule here when it's sure.
- Needs review, called
incompletein the results, are checks axe couldn't finish. A person has to look. - Passes are rules that found something to check, and it was fine.
No violations. So is the card accessible? Not yet. axe checks what a program can check. The DevTools docs say that to know if a page works with a keyboard or a screen reader, you have to try it yourself.
Ravi's menu editor has a spell checker. It underlines "Senchaa" at once. But it can't tell that the iced tea is listed as hot. Every word is spelled right. Only Meena notices, when she reads the menu out loud.
- In real life: The spell checker
- In JavaScript: axe-core
- In real life: "Senchaa", underlined in red
- In JavaScript: A rule break, like a button with no name
- In real life: "Hot" on the iced tea, spelled right but wrong
- In JavaScript: A name that is there, but says the wrong thing
- In real life: Meena reading the menu out loud
- In JavaScript: Testing with a screen reader
Let tools find what they can prove, then check the rest yourself. axe finds rule breaks in open shadow roots. Chrome's tree shows each part's role, name, and state. A person with a checklist finds what neither can.
Does axe-core test shadow DOM?
Yes, when the shadow root is open. axe has checked open roots since version 3.0. It works on the flat tree: open shadow roots, with slotted content where its slot is, as its context docs say.
Not every tool does this. Manuel Matuzović tested a component with three problems in its shadow root. WAVE, another checker, reported zero errors.
Ravi has a quick draft to try, tea-club. It asks people to join the tea club. Here it is, in the tea-club.js tab:
customElements.define("tea-club", class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<p style="color: #bbb">Join the tea club</p>
<span>Email</span> <input type="email">
<button><svg width="16" height="16"><circle cx="8" cy="8" r="6"/></svg></button>`;
}
});- Line 4 attaches a shadow root. The playground below switches its mode.
- Line 5 is light grey text,
#bbb, on white. - Line 6 is an email box. The word Email sits next to it, but nothing ties them together.
- Line 7 is a button with only a circle drawn in it. It has no words at all.
<tea-club></tea-club><script src="tea-club.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-club"); for (const rule of results.violations) { console.log(rule.id, JSON.stringify(rule.nodes[0].target)); } console.log("Violations:", results.violations.length);</script>axe walks into the open shadow root. The grey text, the email box with no label, and the button with no name are all violations. Each target names the host first, then the element inside it.
- Line 5 checks the club.
- Lines 6 to 8 print each failed rule, and where it failed.
- Line 9 prints how many rules failed.
- Open, it prints three rules:
button-name,color-contrast, andlabel. ThenViolations: 3. - Closed, it prints
Violations: 0.
Look at where the button failed: [["tea-club","button"]]. That's a target, axe's address for an element. The outer list has one entry per frame, a page inside a page. When an entry is itself a list, it points into shadow DOM. Its first selector finds the host, and the next one finds the element inside its root.
With a closed root, the same three problems are still there. axe is a script on the page. A closed root's shadowRoot is null to page scripts, as lesson 6.2 showed. So axe has nothing to check. The browser still has all three: lesson 13.1 showed that closed mode doesn't change Chrome's tree.
An inspector checks a block of flats. She goes into every flat with an unlocked door. Her report gives each fault an address: block, flat, then room. A locked flat isn't in the report at all. That doesn't mean its taps work.
- In real life: The inspector
- In JavaScript: axe
- In real life: A flat with an unlocked door
- In JavaScript: A component with an open shadow root
- In real life: A locked flat
- In JavaScript: A closed shadow root
- In real life: "Block 2, flat 4B, the kitchen tap"
- In JavaScript: A target like
[["tea-club","button"]]
Checking one part of a page
Run axe on a whole page, and it checks the page itself too. Try four ways to run it on the tea card's page:
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-card name="Sencha" price="4"></tea-card><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> import "./tea-kit/index.js"; const results = await axe.run(); const ids = (list) => list.map((rule) => rule.id).join(", ") || "none"; console.log("Violations:", ids(results.violations)); console.log("Needs review:", ids(results.incomplete));</script>With no context, axe checks the whole document. Rules about the page itself fail: this example page has no title, no lang, no main landmark, and no h1. They say nothing about the card.
- Line 6 runs axe. The playground changes what it passes to
axe.run(). - Lines 8 and 9 print the names of the rules in each list, or none.
axe.run()fails five page rules, likehtml-has-langanddocument-title."tea-card"printsViolations: noneand one rule to review.fromShadowDomprints the same review item. It belongs to the quantity.excludeprintsnonetwice.
The page rules are about this small example page, which has no title and no lang. They say nothing about the card. With a selector, axe tests only what matches, and everything inside it. Rules about the whole page didn't run.
To reach inside a shadow root, use fromShadowDom. It takes one selector per root, outermost first. include picks what to test, and exclude skips a part of it. The context docs show every form.
fromShadowDom, picks a part to test. At a closed root, it stops.The review item's target is [["tea-card","tea-quantity","#less"]]: the card, then the quantity in the card's root, then the - button in the quantity's root. Why it matters: test the part you own. Then rules about someone else's page don't bury your results.
What can automated accessibility tests miss?
A lot. Deque's README says axe finds about 57% of WCAG issues, on average. It aims to report only real problems, so it leaves out what it can't prove. With components, three kinds of problems get past it.
Roles it can't see
Ravi runs axe on the kit's tabs:
<tea-tabs label="Sencha"> <tea-tab slot="tab">Taste</tea-tab> <tea-tab slot="tab">Brewing</tea-tab> <tea-tab-panel slot="panel">Fresh and grassy.</tea-tab-panel> <tea-tab-panel slot="panel">Steep for 2 minutes.</tea-tab-panel></tea-tabs><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> import "./tea-kit/index.js"; const results = await axe.run("tea-tabs"); for (const rule of results.violations) { console.log(rule.id, rule.impact, JSON.stringify(rule.nodes[0].target)); console.log(rule.nodes[0].any[0].message); } console.log("Violations:", results.violations.length);</script>- Lines 1 to 6 are the tabs from lesson 14.3: two tabs and two panels.
- Line 10 checks them.
- Lines 12 and 13 print each failed rule: its name, how bad it is, its target, and axe's message.
aria-required-children critical [["tea-tabs",".tabs"]]Element has children which are not allowed: tea-tab[tabindex]Violations: 1
A critical violation. But the tabs work. Lesson 14.3 read Chrome's tree, and every tab is there, named and selected. So what did axe see?
In the tabs' shadow root, the row is a div with role="tablist". Its slot holds the tea-tab elements. Each one gets its role, tab, from its internals, as lesson 13.2 showed. And the kit keeps its internals in a private field, #internals.
No script outside the class can read a private field, and axe is a script. So it saw a tab list whose children have no role. Its message names one of them: tea-tab[tabindex].
globalThis._elementInternals, each one is a tab.axe can read internals, but only where a component lists them. Its docs name a few places. One is globalThis._elementInternals, from a draft protocol of the Web Components Community Group. It's a WeakMap: a map whose keys are objects. Each key is an element, and its value is the element's internals.
The protocol keeps internals private in the class, and lists them in one shared map. It calls itself a stopgap, until browsers give tools a way to read the tree. Even then, axe's docs say it reads only the role from internals. Many rules don't run on such an element. The last section gives the kit this fix.
Things it can't judge
Here is the kit's switch with no words, so no name:
<tea-toggle></tea-toggle><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> import "./tea-kit/index.js"; const results = await axe.run("tea-toggle"); console.log("Violations:", results.violations.length);</script>Line 5 checks it, and line 6 prints Violations: 0. Yet Chrome's tree has a switch with no name. A screen reader would say "switch", and nothing else. axe doesn't run its name check on a role from internals. And where it does check names, it can't tell a clear one from a poor one. Add 1 and Add 1 Sencha both pass. Only one says which tea.
Things it can't do
axe doesn't press keys. A span with role="button" and a tabindex passes, even if Space does nothing. Exercise 4 has one. axe doesn't listen either. Whether an announcement comes at the right moment, as lesson 13.5 planned, is something you hear.
What needs review means
The card's review item is a good example. Its - and + buttons show - and +, but their names are One cup less and One cup more. The rule label-content-name-mismatch checks that a name includes the words you see. Here it couldn't decide.
WCAG's page Understanding Label in Name answers it. A symbol isn't a text label, so the name should say what the button does. One cup less is right. A person made that call, not the tool.
Why it matters: a failing test can be the tool's blind spot, and a passing one can hide a real problem. Read each result before you trust it.
How do you see the accessibility tree in Chrome DevTools?
The accessibility tree is what the browser gives screen readers. It has one node for each part that means something, with a role, a name, and states. Lesson 13.1 showed that Chrome builds it from the flat tree. Lesson 13.4 read one element's name in DevTools. This time, read the whole page.
Here is a shop page with four of the kit's components. Open DevTools on its result:
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-card name="Sencha" price="4"></tea-card><tea-toggle>Add milk</tea-toggle><tea-tabs label="Sencha"> <tea-tab slot="tab">Taste</tea-tab> <tea-tab slot="tab">Brewing</tea-tab> <tea-tab-panel slot="panel">Fresh and grassy.</tea-tab-panel> <tea-tab-panel slot="panel">Steep for 2 minutes.</tea-tab-panel></tea-tabs><tea-cart></tea-cart><script type="module"> import "./tea-kit/index.js"; const cart = document.querySelector("tea-cart"); document.addEventListener("tea-add", (event) => cart.add(event.tea, event.quantity));</script>- Lines 2 to 10 are the card, the switch, the tabs, and the cart.
- Line 14 listens for the card's
tea-addevent, and puts the tea in the cart.
Then follow the DevTools docs:
- Right-click the switch in the result, and pick Inspect.
- Open the Accessibility tab, in the same row as Styles. It may hide behind the » button.
- Turn on Show accessibility tree. The Elements panel now shows the whole page's accessibility tree, not its DOM. Turn it off, and the same node stays picked.
- Click any row. Computed properties shows its name, its role, and its states.
Notice what's missing. There's no row for tea-card, and none for a shadow root. The card's article and the buttons from two roots down sit together, as the page shows them. DevTools asks Chrome for this tree through the DevTools protocol, the Chrome team's post explains. A test can ask the same way.
At the entrance of a mall, a list names every shop and what it sells. It doesn't show which walls are behind which unit. It just tells you what's there. That list is what a visitor uses to find the café.
- In real life: The list by the entrance
- In JavaScript: The accessibility tree
- In real life: "Leaf and Kettle, café"
- In JavaScript: A name and a role, like
switch "Add milk" - In real life: "Open" or "closed" next to each shop
- In JavaScript: States, like checked or selected
- In real life: The walls between units
- In JavaScript: Shadow roots, which get no row
Where did a name come from?
When a test says a name is wrong, ask where the name came from. The W3C's Accessible Name and Description Computation 1.2 gives the name rules as steps. The first step that gives text wins. Under Name, DevTools lists each place it looked. Here is where the shop page's controls got their names. Read each row across:
| Control | Chrome's name for it | Where the name came from | Step in the name rules |
|---|---|---|---|
| The card's Add button. | Add 1 Sencha | Its aria-labelledby: the button's own text, then the tea's name. | 2B, LabelledBy. |
| The quantity's - button. | One cup less | Its aria-label. Its text, -, is crossed out under it. | 2D, AriaLabel. |
| The switch. | Add milk | Its content: the words in its slot. | 2F, Name From Content. |
| The tab list. | Sencha | The aria-label tea-tabs writes from its label attribute. | 2D, AriaLabel. |
| The Taste panel. | Taste | Its tab, given as an element through its internals. | 2B, LabelledBy. |
| The cart's Checkout button. | Checkout | Its content. | 2F, Name From Content. |
The switch takes its name from its content, step 2F. The name rules say how that works with shadow DOM. A host's children are its shadow root's children, and a slot's children are the nodes assigned to it. So the words you put inside tea-toggle reach its name, through the slot.
Now inspect the switch with no name, from the last section. Its row says switch, and its name is empty. That's the problem axe passed.
Do other browsers agree? Names and roles were a focus area of Interop 2024, where browser makers aimed to work them out the same way. So a name you check in Chrome is a good guide. Still try another browser before you ship.
Why it matters: the tree is what a screen reader reads. Checking it is the quickest way to hear the page without turning a screen reader on.
How do you test accessibility in component tests?
A check you run by hand is a check you forget. In a test, it runs on every change. Three kinds fit components. The JavaScript path's lesson on testing the DOM and end to end covers the tools in general.
axe in a component test
@open-wc/testing puts together the libraries you need to test components. Its tests run in a test runner that opens a real browser. Its accessibility check is one line:
import { expect, fixture, html } from "@open-wc/testing";
import "../tea-kit/index.js";
describe("tea-tabs", () => {
it("passes axe", async () => {
const tabs = await fixture(html`
<tea-tabs label="Sencha">
<tea-tab slot="tab">Taste</tea-tab>
<tea-tab-panel slot="panel">Fresh and grassy.</tea-tab-panel>
</tea-tabs>`);
await expect(tabs).to.be.accessible();
});
});- Line 1 imports
expect,fixture, andhtml. - Lines 6 to 10 draw the tabs.
fixture()adds them to the page, and the test waits for it. - Line 11 is the check.
to.be.accessible()runs axe on the element, and fails if axe finds violations.
That check comes from chai-a11y-axe, a plugin for the Chai test library. @open-wc/testing adds it for you. Here is the same plugin in a page, on the tea club:
<tea-club></tea-club><script src="tea-club.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> import { expect, use } from "https://esm.sh/@esm-bundle/chai@4.3.4-fix.0"; import { chaiA11yAxe } from "https://esm.sh/chai-a11y-axe@1.5.0?deps=axe-core@4.14.1"; use(chaiA11yAxe); try { await expect(document.querySelector("tea-club")).to.be.accessible(); console.log("Passed"); } catch (error) { const lines = error.message.split("\n"); console.log(lines.filter((line) => line.startsWith("Rule:")).join("\n")); }</script>- Lines 5 to 7 load Chai and the plugin from esm.sh, both pinned, and plug one into the other.
- Line 9 is the same check.
- Line 13 prints the lines of the error that start with
Rule:.
It prints Rule: button-name, Rule: color-contrast, and Rule: label: the club's three violations. On the tea card, the same check passes. Its review item doesn't count, because the plugin reads only violations.
The plugin also takes an ignoredRules option. Don't use it to hide a false alarm like the tabs'. Fix the cause, so the rule keeps guarding everything else.
Role locators in Playwright
Playwright runs real browsers from Node. Its docs say every locator works in shadow DOM by default, with two exceptions: XPath, and closed roots. Its role locators find elements by role and name. Here are lines from a Node script, run on the overview's page:
const less = page.getByRole("button", { name: "One cup less" });
console.log(await less.count());
await page.keyboard.press("Tab");
console.log(await page.evaluate(() => document.activeElement.localName));
console.log(await less.evaluate((button) => button.matches(":focus")));- Line 1 finds the - button by its role and name. It sits two roots down.
- Line 2 counts the matches. It prints
1. - Line 3 presses Tab: a real key press.
- Line 4 asks the document which element has focus. It prints
tea-card. - Line 5 asks the button itself. It prints
true.
Line 4 is the trap from lesson 9.3: document.activeElement gives the outermost host. So ask the element, as line 5 does. Westbrook Johnson adds a second point, from his work on Adobe's Spectrum Web Components: use real key presses. Events you make in code can't move focus with Tab.
Role locators have limits. They don't see roles from internals: lesson 14.3 found no tabs with getByRole("tab"). Playwright's docs add that they don't replace accessibility audits. For those roles, read Chrome's tree through the DevTools protocol, as lesson 13.4 did.
How do you test a web component with a screen reader?
A screen reader reads the accessibility tree out loud, and lets people move through it with keys. Lesson 14.3 started VoiceOver and NVDA and tried them on tabs. In short:
- VoiceOver, on a Mac: Command-F5 turns it on and off. VO means Control and Option together.
- NVDA, on Windows: Control+Alt+N starts it. It has a browse mode for reading, and a focus mode for controls.
What should you listen for? At each control, its role, its name, and its state, like checked or selected. Then do something, and listen for what changed.
Some tools help if you can see the screen:
- VoiceOver's caption panel shows what it is speaking.
- NVDA's Speech Viewer, in its Tools menu, does the same. NV Access made it for sighted developers.
- VoiceOver's rotor (VO-U) lists the page's headings and links. NVDA's Elements list (NVDA+F7) lists links, headings, form fields, buttons, and landmarks.
Read the button names in such a list. Each one should make sense on its own. Here is a script for the shop page. The words differ from one screen reader to the next. The facts don't: every role, name, and state below is in Chrome's tree, and the course's test reads them there. Read each row across:
| Part | What to do | What to listen for |
|---|---|---|
| The card's quantity. | Press Tab to reach the - button, then Tab again. | A button named One cup less, then a button named One cup more. |
| The card's Add button. | Press Tab to reach it, then Enter. | A button named Add 1 Sencha. A moment later, the card's message: Added 1 cup of Sencha to your order. |
| The switch. | Press Tab to reach it, then Space. | A switch named Add milk, off. After Space, the same switch, on. |
| The tabs. | Press Tab to reach Taste, then Right Arrow. | A tab named Taste, selected, in a tab list named Sencha. Then a tab named Brewing, selected. |
| The cart. | Add a tea first. Then press Tab to reach Checkout, and press Enter. | A dialog named Place your order?, with focus on Keep shopping. Escape takes you back to Checkout. |
If a part says less than its row, find it in DevTools' tree. The cause is usually a missing name or state. Why it matters: a script turns "try it with a screen reader" into steps anyone on the team can follow.
What should an accessibility checklist include?
Ravi can't remember every check, every time. So he writes them down, in the order he does them.
Every morning, Meena opens Leaf and Kettle with the same card by the door. Kettles on. Milk fresh. Cups clean. She knows it all by heart. She still reads the card, because the one day she skips it is the day the milk runs out.
- In real life: The card by the door
- In JavaScript: The checklist
- In real life: Kettles on, milk fresh, cups clean
- In JavaScript: Keyboard, zoom, forced colors, motion, direction, screen reader
- In real life: Every morning, in the same order
- In JavaScript: Before every release
Here is Ravi's list for any component. Read each row across:
| Check | How | It passes when |
|---|---|---|
| Keyboard. | Put the mouse away. Use Tab, Shift+Tab, Enter, Space, the arrows, and Escape. | Every control is reachable, works, shows focus, and lets focus leave. |
| Zoom and reflow. | Zoom to 200%. Then make the window 320px wide. | Nothing is cut off, and nothing needs sideways scrolling. |
| Forced colors. | In DevTools' Rendering tab, emulate forced-colors: active. | Every control still shows its edges and its state. |
| Reduced motion. | In the Rendering tab, emulate prefers-reduced-motion: reduce. | Big movement stops, and feedback stays. |
| Right to left. | Put dir="rtl" on a parent. | The component mirrors, and arrow keys follow the line. |
| Screen reader. | Run the script with VoiceOver or NVDA. | Every part says its role, its name, and its state. |
Most rows are lessons in this course. The keyboard is 14.1 and 14.2. Forced colors is 15.1. Reduced motion is 12.7. Right to left is 15.2.
The zoom row comes from WCAG 2.2. Resize Text asks that text can grow to 200% with nothing lost. Reflow asks that content works 320 CSS pixels wide, without scrolling both ways. That's a 1280px window at 400%.
A quick way to try reflow is a box that wide. This page puts the kit in one, and asks every part whether it pokes out:
<link rel="stylesheet" href="tea-kit/tokens.css"><div id="shop" style="inline-size: 320px"> <tea-card name="Masala chai with oat milk" price="5"></tea-card> <tea-toggle>Add milk</tea-toggle> <tea-search></tea-search> <tea-cart></tea-cart></div><script type="module"> import "./tea-kit/index.js"; const edge = document.querySelector("#shop").getBoundingClientRect().right; const all = (root) => [...root.querySelectorAll("*")].flatMap((el) => [el, ...(el.shadowRoot ? all(el.shadowRoot) : [])]); for (const host of document.querySelector("#shop").children) { const out = all(host.shadowRoot).filter((el) => el.getBoundingClientRect().right > edge + 0.5); console.log(host.localName, out.length ? "spills out" : "fits"); }</script>- Line 2 makes the box 320px wide.
- Line 10 finds the box's right edge.
- Line 11 lists every element in a shadow root, and in every root inside it.
- Line 13 keeps the elements that end past the edge. Line 14 prints the result for each component.
It prints tea-card fits, tea-toggle fits, tea-search fits, and tea-cart fits. A box only shows what pokes out, so zoom the real page and look too.
For the keyboard row, Matuzović watches focus with a DevTools live expression of document.activeElement. In shadow DOM, that shows the host. So he adds a second one, for document.activeElement.shadowRoot.activeElement.
Why it matters: a written list catches the check you were sure you did.
Auditing the tea kit before launch
Ravi runs every layer on the shop page. First, axe, one component at a time. Pick a version of the kit:
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-card name="Sencha" price="4"></tea-card><tea-toggle>Add milk</tea-toggle><tea-tabs label="Sencha"> <tea-tab slot="tab">Taste</tea-tab> <tea-tab slot="tab">Brewing</tea-tab> <tea-tab-panel slot="panel">Fresh and grassy.</tea-tab-panel> <tea-tab-panel slot="panel">Steep for 2 minutes.</tea-tab-panel></tea-tabs><tea-cart></tea-cart><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> import "./tea-kit/index.js"; const cart = document.querySelector("tea-cart"); document.addEventListener("tea-add", (event) => cart.add(event.tea, event.quantity)); for (const host of document.querySelectorAll("tea-card, tea-toggle, tea-tabs, tea-cart")) { const results = await axe.run(host); const ids = results.violations.map((rule) => rule.id).join(", "); console.log(`${host.localName}: ${ids || "no violations"}`); }</script>The tabs keep their roles in private internals, so axe sees a tab list with children that have no role.
- Lines 1 to 10 are the shop page, and line 11 loads axe.
- Line 16 picks the four components, in order.
- Line 17 checks each one. Line 19 prints its failed rules, or no violations.
- kitAfter152:
tea-tabs: aria-required-children. The other three printno violations. - kitAfter153: all four print
no violations.
The tabs' failure is the blind spot from earlier. The fix is the kit's new version, kitAfter153. It adds one helper file, tea-kit/internals.js:
/**
* Where the kit's components list their ElementInternals, so accessibility checkers can read them. The Web Components
* Community Group's draft protocol for exposing ElementInternals names this map, and axe-core reads each component's
* role from it. Any script on the page can reach it, so keep nothing secret in a component's internals.
*/
globalThis._elementInternals ??= new WeakMap();
/** Attaches internals to a component, as element.attachInternals() does, and lists them in the map. */
export function attachInternals(element) {
const internals = element.attachInternals();
globalThis._elementInternals.set(element, internals);
return internals;
}- Lines 1 to 5 say what the map is for, and warn what it costs.
- Line 6 makes the map once.
??=only sets it when it'snullorundefined, so a map another library made stays. - Lines 9 to 13 attach a component's internals, list them in the map, and return them.
The six components that attach internals import it, and change one line:
#internals = this.attachInternals(); // kitAfter152
#internals = attachInternals(this); // kitAfter153Line 1 is the old line, and line 2 is the new one. They still keep internals in a private field, so the page can't change a role by mistake. But any script can now reach the map. The protocol accepts that cost to make audits work. Each component's JSDoc and its entry in custom-elements.json say so.
Then the other layers:
- The tree: every control has a role and a name, as the names table showed.
- The keyboard: from the top, Tab goes to One cup less, One cup more, Add 1 Sencha, the Add milk switch, the Taste tab, and the Taste panel. Checkout is off while the cart is empty, so Tab skips it.
- The order: after Add, Checkout joins the Tab order. Enter on it opens the dialog with focus on Keep shopping. Escape takes focus back to Checkout. Place order moves focus to the cart's message, Thanks! Your order is on its way.
- The rest: the reflow check passed. kitAfter153 changes no styles, so forced colors, reduced motion, and right to left pass as their lessons left them.
- Last, Ravi runs the screen reader script with VoiceOver. Then he asks Leela to try it.
The course's test presses every one of those keys in Chrome. Now sort a few problems by the first layer that finds them:
- An email box with no label, in an open shadow root.
- Light grey text on white, in an open shadow root.
- A button with no name, in a closed shadow root.
- A switch whose role comes from its internals, with no words in it.
- Space does nothing on a Save button made from a span.
- After the dialog closes, focus jumps to the top of the page.
- The card announces every press of Add, instead of waiting for the presses to stop.
Sort each problem by the first layer that can find it.
Why it matters: each layer caught something the one before it couldn't. Together, they cover the kit.
Common mix-ups
- "A clean axe run means the component is accessible." No. axe reports what it can prove. Keyboard use, clear names, and announcements need a person.
- "axe can't see inside shadow DOM." No. It checks open roots, and has since version 3.0. It can't open closed ones.
- "You need a special build of axe for shadow DOM." No. Every axe release since 3.0 checks open roots, with no extra setup.
- "A closed shadow root hides content from screen readers." No. Chrome's tree is the same. It hides the content from page scripts, and axe is one.
- "Every axe violation is a real problem." No. The kit's tabs failed because axe couldn't see roles in private internals. Check the tree before you change the component.
- "Needs review items fail to.be.accessible()." No. Only violations fail it. A person decides the rest.
- "document.activeElement tells a test which button has focus." No. It gives the outermost host. Ask the element instead.
- "Playwright's getByRole finds every role." No. It can't enter closed roots, and it doesn't see roles from internals.
Practice exercises
The tea-nav.js tab has a link with only a circle in it. Which rule does axe print? Predict it, then run the page.
<tea-nav></tea-nav><script src="tea-nav.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-nav"); for (const rule of results.violations) console.log(rule.id);</script><tea-nav></tea-nav><script src="tea-nav.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-nav"); for (const rule of results.violations) console.log(rule.id);</script>It prints link-name. The link in the open shadow root holds only an svg circle, so it has no name. axe walks into the open root and finds it.
The button says Add, and its title says Add Sencha to your order. Predict the name Chrome gives it. Then inspect it, and read Name in the Accessibility tab.
<tea-order></tea-order><script src="tea-order.js"></script><tea-order></tea-order><script src="tea-order.js"></script>The name is Add. A button can take its name from its content, and that comes before the title. The title isn't lost: Chrome uses it as the description, Add Sencha to your order.
The club fails three rules. Fix all three in the tea-club.js tab, not the page. What does the page print then?
<tea-club></tea-club><script src="tea-club.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-club"); for (const rule of results.violations) { console.log(rule.id, JSON.stringify(rule.nodes[0].target)); } console.log("Violations:", results.violations.length);</script><tea-club></tea-club><script src="tea-club.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-club"); for (const rule of results.violations) { console.log(rule.id, JSON.stringify(rule.nodes[0].target)); } console.log("Violations:", results.violations.length);</script>The tea-club.js tab changes lines 5 to 7. #555 on white passes contrast. The label names the box, because both sit in the same shadow root. The button's word Join is its name. The page prints Violations: 0.
The page prints Violations: 0. Now press Tab to reach Save Sencha, and press Space. Nothing prints. Make Space and Enter work. What does the first Space print after your fix?
<tea-fave></tea-fave><script src="tea-fave.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-fave"); console.log("Violations:", results.violations.length);</script><tea-fave></tea-fave><script src="tea-fave.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-fave"); console.log("Violations:", results.violations.length);</script>The tea-fave.js tab changes line 4 to a real button. A button clicks itself on Space and Enter, so the click handler runs. The first Space prints Saved: true. axe passed both versions: only pressing Space shows the difference.
The list fails aria-required-children, but its items do have the role listitem. Make axe see it, without making the field public. What does the page print then?
<tea-steps><tea-step>Boil the water.</tea-step><tea-step>Wait 1 minute.</tea-step></tea-steps><script src="tea-steps.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-steps"); for (const rule of results.violations) console.log(rule.id); console.log("Violations:", results.violations.length);</script><tea-steps><tea-step>Boil the water.</tea-step><tea-step>Wait 1 minute.</tea-step></tea-steps><script src="tea-steps.js"></script><script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.1/axe.min.js"></script><script type="module"> const results = await axe.run("tea-steps"); for (const rule of results.violations) console.log(rule.id); console.log("Violations:", results.violations.length);</script>The tea-steps.js tab adds two lines to tea-step's constructor: it makes the map if there's none, and lists its internals there. axe reads role listitem from the map, so the list has its items. The page prints Violations: 0.
The receipt is in a box 320px wide, and it prints tea-receipt spills out. Fix the component, not the page. What does the page print then?
<div id="shop" style="inline-size: 320px"> <tea-receipt></tea-receipt></div><script src="tea-receipt.js"></script><script> const edge = document.querySelector("#shop").getBoundingClientRect().right; const table = document.querySelector("tea-receipt").shadowRoot.querySelector("table"); console.log("tea-receipt", table.getBoundingClientRect().right > edge + 0.5 ? "spills out" : "fits");</script><div id="shop" style="inline-size: 320px"> <tea-receipt></tea-receipt></div><script src="tea-receipt.js"></script><script> const edge = document.querySelector("#shop").getBoundingClientRect().right; const table = document.querySelector("tea-receipt").shadowRoot.querySelector("table"); console.log("tea-receipt", table.getBoundingClientRect().right > edge + 0.5 ? "spills out" : "fits");</script>The tea-receipt.js tab changes line 4 to inline-size: 100%, so the table is as wide as its box. The page prints tea-receipt fits. Keeping 400px and adding max-inline-size: 100% works too.
Check your understanding
Question 1 of 8tea-club.js now attaches a closed shadow root. How many violations does axe.run("tea-club") report?
Read the code, then predictcustomElements.define("tea-club", class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "closed" }).innerHTML = ` <p style="color: #bbb">Join the tea club</p> <span>Email</span> <input type="email"> <button><svg width="16" height="16"><circle cx="8" cy="8" r="6"/></svg></button>`; } });Choose an answer to see the explanation.
Question 2 of 8Which context checks only the quantity inside the tea card's shadow root?
Choose an answer to see the explanation.
Question 3 of 8axe reports no violations for a component. What does that tell you?
Choose an answer to see the explanation.
Question 4 of 8Why did axe flag the kit's tabs in kitAfter152?
Choose an answer to see the explanation.
Question 5 of 8Where does the switch get its name, Add milk?
Choose an answer to see the explanation.
Question 6 of 8Tab lands on the - button inside tea-card. What does document.activeElement give?
Choose an answer to see the explanation.
Question 7 of 8What does to.be.accessible() do with axe's needs-review items?
Choose an answer to see the explanation.
Question 8 of 8How wide is the window that WCAG's Reflow asks content to work in, without sideways scrolling?
Choose an answer to see the explanation.
Key takeaways
- Test in three layers: axe, Chrome's accessibility tree, and a person with a checklist.
- axe walks into open shadow roots, and gives targets with one selector per root. It can't open a closed root.
- Check one part with a selector,
include,exclude, orfromShadowDom, so page rules don't bury your results. - axe sees internals only where a component lists them, in
globalThis._elementInternals. kitAfter153 does. - Show accessibility tree in DevTools shows the whole page's tree, shadow content in place. Under Name, it shows where the name came from.
to.be.accessible()fails only on violations. Playwright's role locators reach into open roots, but not closed roots or roles from internals.- At each control, listen for its role, its name, and its state, and for what changes when you act.
- Keep a checklist: keyboard, zoom and reflow, forced colors, reduced motion, right to left, and a screen reader.
Remember the one-liner.
Let tools find what they can prove, read the tree, then use it yourself before you ship.
Sources
The facts on this page come from these docs, standards, and posts:
- Accessibility features reference, Chrome DevTools docs.
- axe-core README, Deque.
- Web Components Accessibility FAQ: testing, Manuel Matuzović.
- axe-core API: the results object, Deque.
- axe-core context: limit shadow DOM testing, Deque.
- axe-core and ElementInternals, Deque.
- Exposing ElementInternals to accessibility audit tools (draft), Web Components Community Group.
- Understanding SC 2.5.3: Label in Name, W3C.
- Full accessibility tree in Chrome DevTools, Chrome for Developers.
- Accessible Name and Description Computation 1.2, W3C.
- Interop 2024: accessibility, web-platform-tests.
- Testing: testing package, Open Web Components.
- Testing: chai-a11y-axe, Open Web Components.
- Locators: locate in Shadow DOM, Playwright.
- Locators: locate by role, Playwright.
- Testing Accessibility with Shadow Roots, Westbrook Johnson.
- Use the VoiceOver rotor on Mac, Apple.
- Use the VoiceOver caption panel on Mac, Apple.
- NVDA User Guide, NV Access.
- Web Content Accessibility Guidelines (WCAG) 2.2, W3C.
- browser-compat-data, MDN.
Coming next: Joining a form, the first lesson of stage 6. It makes a custom element a real form control, with formAssociated and attachInternals().