toBeAccessibleSwitch()
A switch is an input widget that allows users to choose one of two values: on or off.
Switches are similar to checkboxes and toggle buttons, which can also serve as binary inputs. One difference, however, is that switches can only be used for binary input while checkboxes and toggle buttons allow implementations with the option of supporting a third middle state.
Turn on the lights
Usage
Syntax
- Vanilla JS
- React + Testing Library
test('switch', () => {
document.body.innerHTML = '<div aria-checked="true" id="switch" role="switch">Hey, listen!</div>'
expect(document.getElementById('switch')).toBeAccessibleSwitch()
})
import { render, screen } from '@testing-library/react'
test('switch', () => {
render(
<div aria-checked="true" data-testid="switch" role="switch">
Hey, listen!
</div>,
)
expect(screen.getByTestId('switch')).toBeAccessibleSwitch()
})
Test Summary
There are two different matchers for switches.
The toBeAccessibleSwitch
matcher tests the following:
✓ element has role switch
✓ element has accessible label
✓ element has aria-checked attribute
✓ element toggles aria-checked on Space
✓ element label does not change when state changes
The toBeAccessibleInputSwitch
matcher should be used when the switch element is an input element with type="checkbox"
. This matcher tests the following:
✓ element has role switch
✓ element has accessible label
✓ element toggles checked on Space
✓ element label does not change when state changes
Not Tested
If a set of switches is presented as a logical group with a visible label, either:
- The switches are included in an element with role group that has the property aria-labelledby set to the ID of the element containing the group label.
- The set is contained in an HTML fieldset and the label for the set is contained in an HTML legend element.
WAI-ARIA Roles, States, and Properties
1. The widget has a role
of switch
.
<!-- ✓ element has role switch -->
<div role="switch">hey, listen!</div>
<!-- ❌ element has role switch -->
<span>hey, listen!</span>
2. The switch has an accessible label.
The label can be provided by one of the following:
- Visible text content contained within the element with
role
switch. - A visible label referenced by the value of
aria-labelledby
set on the element withrole
switch. aria-label
set on the element withrole
switch.
Important
It is critical the label on a switch does not change when its state changes.
3. The switch has a valid aria-checked
attribute.
<!-- ✓ element has valid aria-checked -->
<div aria-checked="true" aria-label="Lights" role="switch" />
<!-- ❌ element is missing aria-checked -->
<div aria-label="Lights" role="switch" />
<!-- ❌ element has invalid aria-checked -->
<div aria-checked="on" aria-label="Lights" role="switch" />
Keyboard Interaction
- Space: When focus is on the switch, changes the state of the switch.