Unit Testing Accessibility
In Web Accessibility Hacker Way I mentioned that "only 20% of accessibility requirements can be verified by tools". Nevertheless, it is worth to cover this 20%. Especially, when it is not very hard. You know that having automated test that guard against regressions always pays off in a long run.
As of today the best automatic verification tool for accessibility is aXe.
There is aXe Chrome plugin and aXe Firefox plugin that enables you to run accessibility audit manually:
Running automated tool manually is useful, but it is better to run it automatically as unit test, and incorporate it into your Continuous Integration to run it automatically after every commit.
Running accessibility audit with aXe
You can install aXe with npm:
npm i axe-core
The aXe has a function a11yCheck
that performs accessibility audit on specified HTML Element. You may run it against widgets or partial views on your web app. That function takes 2 parameters:
- HTMLElement to be audited
- callback function that is invoked with
results
parameter
It is useful to print errors to console, as the results.violations
is an array of nested objects with different properties. Many of them are helpful to diagnose the issue.
*a11y is abbreviation for accessibility (similar like i18n for internationalization), 11 is number of letters between 'a' and 'y'
Running aXe with Jasmine 2.x
In order to run aXe with Jasmine, you need to take into account that a11yCheck
is asynchronous. Thus, you need to pass and invoke done
function:
Running aXe with QUnit 2.x
It is similar in QUnit. You also need to invoke done
function, but first you need to get it by calling assert.async()
:
Sample
I created a sample with button and input tag:
This sample is not accessible because input tag does not have a label, and a11yCheck
should report violations. The sample code, with Jasmine and QUnit tests, is available on github: axe-unittests.
Summary
While automated accessibility unit tests are great, you probably still want to use aXe plugin for Chrome to investigate reported violations. It's more convenient, and it has neat user interface, while in unit tests you need to dig in into console errors.
When you start adding accessibility checks for different parts of your system, you may encounter many violations at first. It is better to still add tests, that ignore known violations, and then incrementally fix the issues. This approach prevents regressions, while delaying adding test until all violations are fixed may cause introducing new ones while fixing others.