toBeAccessibleButton()
A button is a widget that enables users to trigger an action or event, such as submitting a form, opening a dialog, canceling an action, or performing a delete operation.
Usage
Syntax
import { screen } from '@testing-library/dom'
test('button', () => {
document.body.innerHTML = '<button data-testid="btn">👍</button>'
expect(screen.getByTestId('btn')).toBeAccessibleButton()
})
Test Summary
The matcher tests the following:
✓ element has role button
✓ element has accessible label
✓ element activated on Space
✓ element activated on Enter
DOM Examples
WAI-ARIA Roles, States, and Properties
1. The button has role
of button
.
<!-- ✓ role is implicit -->
<button>👍</button>
<!-- ✓ role is set with attribute -->
<div role="button">👍</div>
<!-- ❌ FAIL - role is not set or implicit -->
<span>👎</span>
2. The button has an accessible label.
By default, the accessible name is computed from any text content inside the button element. However, it can also be provided with aria-labelledby
or aria-label
.
<!-- ✓ accessible name is text content -->
<button>👍</button>
<!-- ✓ accessible name is set with `aria-label` -->
<button aria-label="👍" />
<!-- ✓ accessible name is set with `aria-labelledby` -->
<body>
<label id="the-label">OK?</label>
<button aria-labelledby="the-label">👍</button>
</body>
<!-- ❌ FAIL - accessible name is not set or implicit -->
<button />
Keyboard Interaction
1. The Space or Enter keys activate the button.
<!-- ✓ HTMLButtonElement will activate -->
<button>👍</button>
<!-- ✓ HTMLDivElement handles onkeydown -->
<div onkeydown="javascript: customHandler" role="button">👍</div>
<!-- ❌ FAIL - HTMLDivElement will need Javascript -->
<div>click me</div>