Role options and aria snapshots

Filter roles by their state

getByRole() accepts options that match ARIA state, so you can find "the selected tab" or "the expanded question" without knowing which one it is:

await expect(page.getByRole('tab', { selected: true })).toHaveText('Profile');

await page.getByRole('button', { name: 'Can I run tests in parallel?' }).click();
await expect(page.getByRole('button', { expanded: true })).toHaveCount(1);

await page.getByRole('button', { name: 'Bold' }).click();
await expect(page.getByRole('button', { name: 'Bold', pressed: true })).toBeVisible();

await expect(page.getByRole('heading', { level: 3 })).toHaveCount(3); // the questions

The options are checked, disabled, expanded, level, pressed and selected.

Widgets are driven by the keyboard too

await page.getByRole('tab', { name: 'Profile' }).focus();
await page.keyboard.press('ArrowRight');
await expect(page.getByRole('tab', { name: 'Security' })).toBeFocused();
await expect(page.getByRole('tabpanel')).toHaveText(/Two-factor/);

Assert a whole structure: toMatchAriaSnapshot()

An aria snapshot describes the accessibility tree: roles, names and states, written as YAML. One assertion checks a whole widget:

await expect(page.getByRole('tablist')).toMatchAriaSnapshot(`
  - tablist "Account settings":
    - tab "Profile" [selected]
    - tab "Security"
    - tab "Billing"
`);

You do not have to write snapshots by hand. await locator.ariaSnapshot() returns the YAML for any element. Paste it in, then trim it down to what matters. Text can be a regular expression, such as - tabpanel: /Two-factor/.

Aria snapshots fail when roles or names change, which is exactly what screen-reader users would notice. They also catch accessibility regressions.

Tabs

Your name and photo are visible to your team.

Accordion

Toggle buttons

Formats: none