Skip navigation and go to content
All Articles

Unit Testing for Accessibility

Marcy SuttonMarcy Sutton

Like most areas of web development, testing for accessibility can benefit from automation.

There are several different types of tests you can write, each with their own time and place to be most useful. Today we'll talk about the role of Unit Tests when testing accessibility.

Unit tests are concerned with small, isolated pieces of functionality that don't rely on things like API calls or other external services.

Often unit tests for accessibility will make sure that accessibility information makes it into the right place in a component for digesting in screen readers, or test internal interaction APIs.


Here's an example from Testing Accessibility that uses Jest and Testing Library to see if a button within a custom dropdown is properly labeled:

it('renders activatorText', () => {
    const activatorText = 'Settings'
    const { getByRole } = render(<Dropdown activatorText={activatorText} />)

    const button = getByRole('button')
    expect(button).toHaveTextContent('Settings')
  })

It's possible to make browser-based DOM assertions with unit tests, though the capabilities depend on the library you use.

One popular choice that I like to use is Testing Library because of the available queries and interaction events.

Here's another example with Testing Library that will fail if the dropdown button isn't a real button, but a div instead:

it('renders a dropdown button', () => {
    const activatorText = 'Options'
    const dropdown = render(<Dropdown activatorText={activatorText} />)

    const activator = dropdown.getByTestId('dropdown-activator')
    activator.focus()

    expect(activator).toHaveFocus()
  })

I like this toolset because your tests become a contract for accessible user interface components. If a button regresses into a non-focusable DIV like our above example, the test will fail since DIVs aren't reachable or operable by keyboard.

While there's a lot more that we can do with unit testing–I'll go into more depth in the full Testing Accessibility workshop series–there are plenty of scenarios that benefit from different, less isolated techniques.

Join my exclusive 6-part email course

Learn more about building and testing accessible web applications.