Sub topic 14
Testing keyboard and screen reader behavior
This chapter assumes you can write React function components with hooks and basic TypeScript. It also assumes you have a project with shadcn/ui components added, and that you have met the accessibility basics: roles, focus, and keyboard interaction. Radix UI primitives supply most of the behavior in shadcn/ui components. You still need to test the result, because your own markup, classes, and composition can break what the primitive provides.
What you are testing
A Radix primitive is tested by its authors. Your code is not. These are the things you can break in a copied component:
- Removing a
Dialog.TitleorDialog.Description, which removes the accessible name and description. - Hiding the focus ring with
outline-noneand no replacement style. - Using
asChildwith a child that cannot receive a ref or props. - Replacing a
buttonwith adivthat has anonClick. - Hiding an element with
display: nonewhen you only meant to hide it visually. - Using an
inputwith no label.
Testing has three layers. Each catches different problems.
| Layer | Tool | Catches | Misses |
|---|---|---|---|
| Automated rules | jest-axe, axe DevTools | Missing labels, invalid ARIA, bad roles | Wrong tab order, confusing announcements |
| Behavior tests | Testing Library, user-event | Focus movement, Escape handling, keyboard activation | Real screen reader output |
| Manual checks | Keyboard, NVDA, VoiceOver | Real usability | Nothing automated, but it is slow |
Setting up the test tools
This example uses Vitest, Testing Library, and jest-axe. Install them as development dependencies.
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom jest-axe @types/jest-axeConfigure Vitest to use a DOM environment and a setup file.
// vitest.config.ts
import { defineConfig } from "vitest/config"
import react from "@vitejs/plugin-react"
import path from "node:path"
export default defineConfig({
plugins: [react()],
resolve: { alias: { "@": path.resolve(__dirname, "./src") } },
test: {
environment: "jsdom",
setupFiles: ["./src/test-setup.ts"],
globals: true,
},
})// src/test-setup.ts
import "@testing-library/jest-dom/vitest"
import { expect } from "vitest"
import { toHaveNoViolations } from "jest-axe"
expect.extend(toHaveNoViolations)Automated checks with axe
axe is a rule engine. It reads the rendered DOM and reports violations of WCAG rules. It runs fast, so it belongs in every component test.
Here is a test for the ConfirmDialog from the Radix chapter. The dialog is closed at first, so the test opens it before running axe.
// src/components/confirm-dialog.test.tsx
import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { axe } from "jest-axe"
import { describe, expect, it } from "vitest"
import { ConfirmDialog } from "./confirm-dialog"
describe("ConfirmDialog", () => {
it("has no axe violations when open", async () => {
const user = userEvent.setup()
render(<ConfirmDialog />)
await user.click(screen.getByRole("button", { name: "Delete item" }))
const dialog = await screen.findByRole("dialog")
expect(await axe(dialog)).toHaveNoViolations()
})
})Passing dialog to axe scopes the scan to that element. Scanning document.body also works, but Radix marks the rest of the page as hidden while a modal is open, and the results are harder to read.
Axe cannot tell you whether the page is usable. A dialog with a title that says "Untitled" passes. A tab order that jumps around the page passes. Treat a clean axe run as the minimum.
Testing keyboard behavior
user-event simulates real user input. It fires the full sequence of events for a key press, including keydown, keyup, and the default browser actions. Prefer it over fireEvent, which fires one event and skips the rest.
A good keyboard test describes what a person does and what they should perceive. Three behaviors matter most for a modal dialog:
- Focus moves into the dialog when it opens.
- Tab stays inside the dialog.
- Escape closes the dialog and focus returns to the trigger.
it("moves focus into the dialog and restores it on Escape", async () => {
const user = userEvent.setup()
render(<ConfirmDialog />)
const trigger = screen.getByRole("button", { name: "Delete item" })
await user.click(trigger)
const dialog = await screen.findByRole("dialog")
expect(dialog).toContainElement(document.activeElement as HTMLElement)
await user.keyboard("{Escape}")
expect(screen.queryByRole("dialog")).not.toBeInTheDocument()
expect(trigger).toHaveFocus()
})
it("keeps Tab inside the dialog", async () => {
const user = userEvent.setup()
render(<ConfirmDialog />)
await user.click(screen.getByRole("button", { name: "Delete item" }))
const dialog = await screen.findByRole("dialog")
for (let i = 0; i < 5; i++) {
await user.tab()
expect(dialog).toContainElement(document.activeElement as HTMLElement)
}
})The second test presses Tab more times than the dialog has focusable elements. If focus ever lands outside, the assertion fails.
Test keyboard activation
A native button fires click on Enter and Space. A div with role="button" does not, unless you write the handlers. When you change a component through asChild, test that the keys still work.
import { Button } from "@/components/ui/button"
it("activates a link-styled button with Enter", async () => {
const user = userEvent.setup()
const onClick = vi.fn()
render(
<Button asChild>
<a href="#docs" onClick={(e) => { e.preventDefault(); onClick() }}>
Read the docs
</a>
</Button>
)
await user.tab()
expect(screen.getByRole("link", { name: "Read the docs" })).toHaveFocus()
await user.keyboard("{Enter}")
expect(onClick).toHaveBeenCalledTimes(1)
})This test also confirms the role. With asChild, the element is a link, not a button, and a screen reader announces it as a link. Query by getByRole("link") so the test fails if someone changes the element.
Prefer role queries
Testing Library queries by role use the same accessibility tree that assistive technology uses. getByRole("button", { name: "Delete item" }) passes only if the element has the right role and an accessible name. Avoid getByTestId for interactive elements. A test id succeeds even when the element has no name.
What jsdom cannot tell you
jsdom implements the DOM, not rendering. Some Radix components use browser features jsdom lacks, such as ResizeObserver, PointerEvent details, or scrollIntoView. A Select or DropdownMenu test may throw errors for these. Add small stubs in your setup file.
// add to src/test-setup.ts
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
globalThis.ResizeObserver ??= ResizeObserverStub as typeof ResizeObserver
Element.prototype.scrollIntoView ??= () => {}
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.releasePointerCapture ??= () => {}If a test depends on real layout or real focus behavior, use a browser test runner such as Playwright. Playwright can also run axe against a full page through @axe-core/playwright.
Manual keyboard pass
Automated tests do not replace ten minutes with the keyboard. Unplug the mouse, or just do not touch it, and work through the page.
- Press Tab from the top of the page. Check that focus visits every interactive element in a sensible order.
- Look for a visible focus indicator on every stop. shadcn/ui buttons use
focus-visible:ring-2, but your overrides may remove it. - Press Enter and Space on buttons, and Enter on links.
- Open each overlay with the keyboard, then press Escape. Focus should return to the control that opened it.
- Use arrow keys inside menus, tabs, radio groups, and selects. These widgets use one tab stop and arrow keys inside, so Tab should leave the widget, not move through its items.
Manual screen reader pass
A screen reader reads the accessibility tree aloud. Test with at least one reader on its common browser pairing.
| Platform | Screen reader | Common browser | Start and stop |
|---|---|---|---|
| Windows | NVDA (free) | Firefox or Chrome | Ctrl+Alt+N to start, Insert+Q to quit |
| macOS | VoiceOver | Safari | Cmd+F5 |
| iOS | VoiceOver | Safari | Settings, Accessibility |
Listen for these things:
- Names: each control announces a meaningful name. "Button" alone is a bug, as is an icon-only button with no
aria-label. - Role and state: a toggle says whether it is on, and a collapsed section says "collapsed".
- Dialog announcement: opening a dialog should announce its title, and often its description.
- Errors: a form error should be announced when it appears. In the form from the validation chapter,
role="alert"does this. - Hidden content: content behind a modal should not be reachable.
For an icon-only button, the fix is a name that is not visible.
import { X } from "lucide-react"
import { Button } from "@/components/ui/button"
export function CloseButton({ onClose }: { onClose: () => void }) {
return (
<Button variant="outline" size="sm" onClick={onClose}>
<X aria-hidden="true" />
<span className="sr-only">Close</span>
</Button>
)
}sr-only is a Tailwind utility that hides text visually but keeps it in the accessibility tree. aria-hidden="true" on the icon stops the screen reader from announcing the SVG.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Console warning about missing `Title` or `aria-describedby` | Removed or reordered `Dialog.Title` or `Dialog.Description` | Restore them, or wrap the title in `VisuallyHidden` |
| axe reports "button has no discernible text" | Icon-only button with no label | Add `aria-label` or an `sr-only` span |
| Escape does not close in a test | Used `fireEvent.keyDown` on the wrong element | Use `user.keyboard("{Escape}")` |
| Test throws `ResizeObserver is not defined` | jsdom lacks the API | Add the stub in the setup file |
| `getByRole` finds nothing inside an open modal | Querying an element hidden from the tree by `aria-hidden` on a parent | Query from the dialog element, or use `{ hidden: true }` only if you intend it |
| Focus ring missing | `outline-none` without a `focus-visible` style | Add `focus-visible:ring-2` |
A short checklist
Run through this list for each new component or each override you make to a copied component.
- Does it have an accessible name that makes sense out of context?
- Can you reach and operate it with only the keyboard?
- Is focus visible, and does it move where you expect?
- Does axe report zero violations in each state: closed, open, error, and disabled?
- Did you listen to it once with a screen reader?
Exercise
A teammate changes <Button>Save</Button> to <Button asChild><div onClick={save}>Save</div></Button> and the unit test still passes because it queries getByTestId("save"). Name two keyboard or screen reader problems this causes and the test change that would catch them.
Show answer
A div is not focusable, so Tab skips it, and it does not fire click on Enter or Space, so keyboard users cannot save. A screen reader also announces no button role. Query with getByRole("button", { name: "Save" }), which fails because the div has no role. Then use user.tab() and user.keyboard("{Enter}") to check focus and activation. The fix is to use a real button, or a link for navigation.
Exercise
Write the assertion lines that check a dialog returns focus to its trigger after the Close button is clicked. Assume trigger is the opening button and user comes from userEvent.setup().
Show answer
await user.click(screen.getByRole("button", { name: "Cancel" })); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); expect(trigger).toHaveFocus(). Radix restores focus to the trigger when the dialog closes, so this test fails if the trigger was unmounted or the dialog was built without Radix.