EthicsComputerCourses
Join training +91 90532 10052

Accessibility Automated Testing

HTML · Lesson 207 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to run axe-core in the browser and inside Playwright tests, check a list of pages with pa11y-ci, read Lighthouse's accessibility score, lint React code with eslint-plugin-jsx-a11y, and turn the results into a build that fails only when someone adds a new problem.

What you should know first: WCAG Accessibility Auditing (the full manual audit), Lighthouse & HTML Auditing, Playwright Browser Testing and HTML Integration with React. The audit lesson explains why tools find only part of the problems. This lesson is about running them well and often.

Where automated checks fit

A manual audit is like the yearly fitness check of a bus at the RTO: thorough, slow and occasional. Automated checks are the conductor glancing at the tyres before every trip. They are quick, they repeat without getting bored, and they catch the obvious faults the moment they appear.

StageToolCatches problems
While typing codeeslint-plugin-jsx-a11yIn JSX source, before it runs
In the browseraxe DevTools extension, axe-core scriptOn the rendered page you are looking at
In end-to-end tests@axe-core/playwrightOn each page and state your tests visit
In CI for many URLspa11y-ci, Lighthouse CIAcross a list of pages on every push

Versions used in this lesson (November 2026): axe-core 4.14.0, @axe-core/playwright 4.14.0, Playwright 1.65.1, pa11y-ci 5.0.0 (which runs pa11y 10), Lighthouse 13.6.0, ESLint 9.39 and eslint-plugin-jsx-a11y 6.10.2.

How axe-core reports results

axe-core is Deque's open-source rules engine. Most tools in this lesson run it inside. Each rule has tags: wcag2a, wcag2aa, wcag21aa and wcag22aa mark WCAG levels and versions, and best-practice marks advice that is not a WCAG failure. axe.run() returns four arrays:

  • violations: rules that failed, each with an impact (minor, moderate, serious or critical) and the failing nodes.
  • incomplete: "needs review". axe could not decide, for example text on a gradient. A human must check these.
  • passes and inapplicable: rules that passed, or had nothing to test.

Step 1: run axe-core on a page

This page loads axe-core 4.14.0 from the jsDelivr CDN and tests only the dashed box. Press Run axe.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>axe-core in the browser</title>
  <script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.0/axe.min.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    #app { border: 2px dashed #90a4ae; padding: 12px; }
    .hint { color: #aaa; }
    .promo { background: linear-gradient(90deg, #fff3e0, #ff7043); color: #fff; padding: 8px; }
    li { margin: 4px 0; }
  </style>
</head>
<body>
  <div id="app">
    <img src="https://course.ethicscomputer.in/assets/samples/logo.svg" width="240" height="80">
    <h2>Register for the Kochi Book Fair</h2>
    <input type="text" placeholder="Full name">
    <p class="hint">We will send your entry pass by SMS.</p>
    <select><option>Day 1</option><option>Day 2</option></select>
    <button type="button"><svg width="16" height="16" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4"/></svg></button>
    <p class="promo">Early bird: ₹50 off</p>
  </div>
  <p><button type="button" id="run">Run axe</button></p>
  <div id="out"></div>

  <script>
    function list(title, items) {
      const h = document.createElement("h3");
      h.textContent = title;
      const ul = document.createElement("ul");
      for (const text of items) {
        const li = document.createElement("li");
        li.textContent = text;
        ul.append(li);
      }
      document.querySelector("#out").append(h, ul);
    }

    document.querySelector("#run").addEventListener("click", async () => {
      document.querySelector("#out").replaceChildren();
      const results = await axe.run("#app", {
        runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"] }
      });
      list(`axe ${axe.version}: ${results.violations.length} violations`, results.violations.map((v) =>
        `${v.impact} | ${v.id} | ${v.help} | ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`));
      list("Needs review (incomplete)", results.incomplete.map((v) => `${v.id}: ${v.nodes.length} element(s)`));
      list("Summary", [`${results.passes.length} rules passed, ${results.inapplicable.length} not applicable`]);
    });
  </script>
</body>
</html>

You should see four violations: image-alt and select-name and button-name (critical) and color-contrast on the grey hint (serious). The gradient promo lands in Needs review, because axe cannot measure contrast against a gradient. Notice what is missing: the name field with only a placeholder passed. axe accepts a placeholder as an accessible name, even though it vanishes when you type. Add a <label>, an alt, a label for the select and an aria-label for the icon button, and run again.

Step 2: axe inside Playwright tests

The browser extension needs a person to click it. In a test suite, @axe-core/playwright runs axe on every page your tests open, including states such as an open menu or a form showing errors. Here it checks a registration page served from a local PHP server:

JavaScript
// tests/a11y.spec.mjs
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";

test("register page has no WCAG A/AA violations", async ({ page }) => {
  await page.goto("/register");
  const results = await new AxeBuilder({ page })
    .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"])
    .analyze();

  const summary = results.violations.map((v) => `${v.impact} ${v.id} (${v.nodes.length})`);
  console.log(summary.join("\n"));
  expect(summary).toEqual([]);
});
Output
critical button-name (1)
serious color-contrast (1)
serious html-has-lang (1)
critical image-alt (1)
  x  1 tests\a11y.spec.mjs:4:1 › register page has no WCAG A/AA violations (1.3s)

Comparing a short summary array, rather than the whole results object, keeps the failure message readable. AxeBuilder also has .include() and .exclude() to limit the area tested, and .disableRules() to switch off one rule. Use them sparingly and write down why.

Step 3: many pages with pa11y-ci

pa11y-ci visits a list of URLs and fails with exit code 2 when a page has errors. It can use two engines: axe and HTML_CodeSniffer (htmlcs). Save this as .pa11yci.json:

JSON
{
  "defaults": {
    "standard": "WCAG2AA",
    "runners": ["axe", "htmlcs"],
    "timeout": 30000,
    "chromeLaunchConfig": {
      "executablePath": "C:/Program Files/Google/Chrome/Application/chrome.exe"
    }
  },
  "urls": [
    "http://127.0.0.1:8206/register",
    "http://127.0.0.1:8206/cards"
  ]
}
Terminal
npx pa11y-ci
Output
Running Pa11y on 2 URLs:
 > http://127.0.0.1:8206/register - 10 errors
 > http://127.0.0.1:8206/cards - 0 errors

Errors in http://127.0.0.1:8206/register:

 • This textinput element does not have a name available to an accessibility
   API. Valid names are: label element, title , aria-label , aria-labelledby .

   (html > body > main > form > input:nth-child(1))

   <input type="text" name="name" placeholder="Full name">

✘ 1/2 URLs passed

The full output lists all ten errors; this shows one. The two engines overlap, so "10 errors" includes the same missing alt and lang reported twice. They also disagree: htmlcs flagged both placeholder-only fields, which axe passed. Running both gives better coverage. The executablePath line points at an installed Chrome; leave it out if pa11y-ci's own browser download works on your machine.

Lighthouse and eslint-plugin-jsx-a11y

Lighthouse runs a subset of axe rules and turns them into a score. On the same page it scored 62. A short script printed each failed audit from the JSON report with its weight:

Output
10 button-name | Buttons do not have an accessible name
7 color-contrast | Background and foreground colors do not have a sufficient contrast ratio.
3 heading-order | Heading elements are not in a sequentially-descending order
7 html-has-lang | `<html>` element does not have a `[lang]` attribute
10 image-alt | Image elements do not have `[alt]` attributes

The score is the weighted share of passed audits, and the weights follow axe's impact (critical 10, serious 7, moderate 3). It also listed ten "manual" items, such as logical focus order, which no score covers.

eslint-plugin-jsx-a11y checks React's JSX while you type, before anything renders. With ESLint 9 flat config:

JavaScript
// eslint.config.js
import jsxA11y from "eslint-plugin-jsx-a11y";

export default [
  {
    files: ["src/**/*.jsx"],
    ...jsxA11y.flatConfigs.recommended,
    languageOptions: {
      ...jsxA11y.flatConfigs.recommended.languageOptions,
      parserOptions: { ecmaFeatures: { jsx: true } },
    },
  },
];

It found five problems in a saree card component (path shortened):

Output
src\SareeCard.jsx
  3:5   error  Visible, non-interactive elements with click handlers must have at least one keyboard listener                                                                                                                 jsx-a11y/click-events-have-key-events
  3:5   error  Avoid non-native interactive elements. If using native HTML is not possible, add an appropriate role and support for tabbing, mouse, keyboard, and touch inputs to an interactive content element              jsx-a11y/no-static-element-interactions
  4:7   error  img elements must have an alt prop, either with meaningful text, or an empty string for decorative images                                                                                                      jsx-a11y/alt-text
  7:7   error  Anchor used as a button. Anchors are primarily expected to navigate. Use the button element instead. Learn more: https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/anchor-is-valid.md  jsx-a11y/anchor-is-valid
  8:15  error  The value for aria-pressed must be a boolean or the string "mixed"                                                                                                                                             jsx-a11y/aria-proptypes

✖ 5 problems (5 errors, 0 warnings)

Line 3 was a clickable <div>, line 7 an <a href="#"> used as a button, line 8 aria-pressed="yes". A linter sees code, not the page: it cannot check contrast, and it also passed an <input placeholder="Qty"> with no label.

What automation cannot catch

The register page also had a link reading "Click here". axe, pa11y-ci and Lighthouse all passed it, and none of them can tell whether alt text is accurate. Automation also misses:

  • whether focus order and visible focus make sense when you press Tab;
  • keyboard traps and broken arrow keys in custom widgets such as tabs and date pickers;
  • what a screen reader actually announces after a change, such as a form error;
  • whether headings, labels and error messages are clear in plain language;
  • captions that exist but are wrong.

So automated tests are a floor, not a finish line. Follow them with the manual checks from WCAG Accessibility Auditing.

Triaging results

A first scan of a large site can report hundreds of issues. Sort them before you fix anything:

  1. Step 1: group by rule and component. Forty button-name failures from one header template are one fix, not forty.
  2. Step 2: rank by impact and journey. A critical failure on checkout beats a moderate one on an old blog post.
  3. Step 3: check "needs review" items by hand and record your decision.
  4. Step 4: confirm suspected false positives with a screen reader before you suppress a rule, and note the reason in the code.
  5. Step 5: file tickets with the rule ID, selector, WCAG criterion and page, so the developer can reproduce them.

Step 4: stop regressions with a baseline

Legacy sites cannot fix everything at once, but they can refuse to get worse. A baseline lists known, ticketed issues. The build fails only on issues not in the list, and entries that disappear are reported as fixed, so the list only shrinks. Tick the box to simulate a new commit.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>Accessibility baseline</title>
  <script src="https://cdn.jsdelivr.net/npm/axe-core@4.14.0/axe.min.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    #app { border: 2px dashed #90a4ae; padding: 12px; }
    .hint { color: #aaa; }
    .fail { color: #b00020; font-weight: bold; }
  </style>
</head>
<body>
  <div id="app">
    <label for="mobile">Mobile number</label>
    <input id="mobile" type="tel" autocomplete="tel">
    <p class="hint">We never share your number.</p>
  </div>
  <p><label><input type="checkbox" id="commit"> Add the new commit (an icon button and a photo)</label></p>
  <button type="button" id="run">Run the check</button>
  <ul id="out"></ul>

  <script>
    // Known issues, each with a ticket. Key: rule id | CSS selector
    const baseline = new Map([
      ["color-contrast|.hint", "A11Y-12"],
      ["image-alt|#hero", "A11Y-15"]
    ]);

    document.querySelector("#run").addEventListener("click", async () => {
      const app = document.querySelector("#app");
      app.querySelector(".new")?.remove();
      if (document.querySelector("#commit").checked) {
        app.insertAdjacentHTML("beforeend",
          '<div class="new"><button type="button">&#9733;</button> <img src="https://course.ethicscomputer.in/assets/samples/icon.svg" width="64" height="64"></div>');
        app.querySelector(".new button").textContent = "";
      }
      const results = await axe.run(app, { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag22aa"] } });
      const found = results.violations.flatMap((v) => v.nodes.map((n) => `${v.id}|${n.target.join(" ")}`));
      const lines = [];
      for (const key of found) {
        lines.push(baseline.has(key) ? `Known (${baseline.get(key)}): ${key}` : `NEW: ${key}`);
      }
      for (const key of baseline.keys()) {
        if (!found.includes(key)) lines.push(`Fixed, remove from baseline: ${key}`);
      }
      const newCount = found.filter((key) => !baseline.has(key)).length;
      lines.push(newCount ? `Build FAILS: ${newCount} new issue(s)` : "Build passes: no new issues");
      document.querySelector("#out").replaceChildren(...lines.map((text) => {
        const li = document.createElement("li");
        li.textContent = text;
        if (text.startsWith("NEW") || text.startsWith("Build FAILS")) li.className = "fail";
        return li;
      }));
    });
  </script>
</body>
</html>

The first run shows the known contrast issue, reports image-alt|#hero as fixed (it is no longer on the page) and passes. With the new commit ticked, the icon button and the photo appear as NEW and the build fails.

In CI you can keep the same idea with built-in settings:

  • pa11y-ci: give a legacy URL a "threshold" in its config object, such as { "url": "...", "threshold": 10 }. A page passes while it has that many issues or fewer; lower the number as you fix them.
  • Lighthouse CI: assert "categories:accessibility": ["error", { "minScore": 0.9 }], explained in Lighthouse Performance Auditing.
  • Playwright: compare violations with a baseline file, exactly as the tryit does.

Common mistakes

  • Treating zero violations as "accessible". It only means no automated rule failed.
  • Ignoring "needs review". Incomplete items are often real contrast problems.
  • Scanning only the page as it loads. Open menus, dialogs and error states, then scan again.
  • Disabling a noisy rule for the whole site. Exclude the one element and record why.
  • Running a tool once. Value comes from running it on every change.

Interview questions

1. What does axe-core return, and what is the "incomplete" array?

axe.run() returns violations, passes, incomplete and inapplicable. Violations failed a rule and carry an impact level and the failing nodes. Incomplete means axe could not decide, for example contrast over a gradient or image, so a person must review it.

2. How do you add accessibility checks to Playwright tests?

Install @axe-core/playwright, create new AxeBuilder({ page }), optionally limit it with withTags() or include(), and call analyze(). Assert that the violations array is empty, or that it matches a known baseline. Run it after the test has opened menus or dialogs, so those states are checked too.

3. Why might pa11y with htmlcs report an error that axe does not?

They are different rule engines with different rules. In our test, htmlcs flagged inputs labelled only by a placeholder, while axe accepted the placeholder as a name. Using both engines widens coverage, though the totals then include duplicates.

4. What can eslint-plugin-jsx-a11y find, and what can it not?

It checks JSX source for problems such as missing alt props, invalid ARIA values and click handlers on non-interactive elements. It cannot see the rendered page, so contrast, focus order and runtime states are outside its reach.

5. How do you stop accessibility regressions on a site with many existing issues?

Record known issues in a baseline with tickets and fail the build only on new ones, or set per-page thresholds that you lower over time. Remove baseline entries when they are fixed, so the list only shrinks.

Key points

  • Automated checks run at four stages: linting JSX, the browser, end-to-end tests and CI across many URLs.
  • axe-core returns violations with an impact, plus incomplete items that need a human decision.
  • @axe-core/playwright checks every page and state your tests reach; pa11y-ci checks lists of URLs with axe and htmlcs.
  • Lighthouse's accessibility score is a weighted subset of axe rules; eslint-plugin-jsx-a11y works on source code only.
  • No tool judges alt text quality, link text such as "Click here", focus order or announcements.
  • Triage by rule, component, impact and user journey; block regressions with baselines and thresholds.

Exercise

Pick two pages you built, such as a contact form and a product page. Write a Playwright test that runs AxeBuilder on each page with WCAG A and AA tags, and also on the contact form after submitting it empty so the errors show. Save today's violations as a baseline file of rule|selector keys and make the test fail only on new ones. Then add a pa11y-ci config for the same two URLs with both runners, and list one problem each tool missed that you found by hand.

Show solution
JavaScript
// tests/a11y-baseline.spec.mjs
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";
import { readFileSync } from "node:fs";

const baseline = new Set(JSON.parse(readFileSync("a11y-baseline.json", "utf8")));
const tags = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];

async function newIssues(page) {
  const results = await new AxeBuilder({ page }).withTags(tags).analyze();
  return results.violations
    .flatMap((v) => v.nodes.map((n) => `${v.id}|${n.target.join(" ")}`))
    .filter((key) => !baseline.has(key));
}

test("product page", async ({ page }) => {
  await page.goto("/product");
  expect(await newIssues(page)).toEqual([]);
});

test("contact form with errors showing", async ({ page }) => {
  await page.goto("/contact");
  await page.getByRole("button", { name: "Send" }).click();
  expect(await newIssues(page)).toEqual([]);
});

a11y-baseline.json holds an array such as ["color-contrast|.footer-note"]. A typical manual finding: the error messages were not linked to their fields with aria-describedby, so a screen reader did not read them; no tool reported it.

Quick Quiz

1. axe-core puts contrast on a gradient background into which array?

2. Which tool checks JSX source code before the page renders?

3. A legacy page has 12 known issues. What stops new ones without blocking every build?

4. In the lesson's tests, which problem did no automated tool report?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call