Duong Hoang Nam

Search Articles

Find AI, technology, and programming guides

Press Esc to closeFull Search Page →
Tutorials

How to Automate Accessibility Testing in Astro with Playwright, axe-core, and GitHub Actions (2026 Guide)

Automate Astro accessibility testing with Playwright, axe-core and GitHub Actions. Scan key pages, catch WCAG issues and review CI reports.

By Duong Hoang Nam
How to Automate Accessibility Testing in Astro with Playwright, axe-core, and GitHub Actions (2026 Guide)

Accessibility is part of website quality, not a final visual polish step. A site may load quickly, score well in Lighthouse, and still contain unlabeled controls, keyboard traps, or dialogs that are difficult to use without a mouse. These issues often appear after seemingly harmless changes to navigation, forms, or reusable components.

For an Astro blog, we can detect some of these regressions automatically. Playwright opens the built website in a browser, axe-core checks the rendered page against automated accessibility rules, and GitHub Actions runs those tests on pull requests.

In this tutorial, you’ll build a practical accessibility-testing workflow for a static Astro site. You’ll learn how to scan critical routes, inspect violations, publish CI reports, and add manual checks that automation cannot replace.

Scope: This is a reference implementation, not a claim that a particular production site passes WCAG. The examples assume npm, an Astro site with a working build and preview script, and GitHub-hosted source code.

1. Why Test Accessibility Before Deployment?

Accessibility regressions may be introduced by ordinary maintenance: a custom search overlay receives a new close button without an accessible name, a form loses its visible label, or a text color no longer has sufficient contrast. Such errors can affect people using assistive technology as well as visitors navigating by keyboard.

A pre-deployment test provides earlier feedback than discovering the problem after publishing. It also gives contributors a repeatable way to check shared components.

Automated tests should be one layer of quality assurance, alongside human review. The Playwright accessibility guide explicitly cautions that not all accessibility problems can be discovered automatically.

2. The Testing Architecture

Our testing pipeline uses the following sequence:

Pull request
    |
    v
Install dependencies
    |
    v
Build Astro to dist/
    |
    v
Start Astro preview server
    |
    v
Playwright visits selected routes
    |
    v
axe-core scans the rendered DOM
    |
    +--- Violations ---> Fail the test, save report
    |
    +--- No detected violations ---> Continue review

This tests the built version of the website, rather than relying only on static source inspection. The preview server is managed by Playwright during test runs.

Automated Astro accessibility CI pipeline from pull request through build, Playwright, axe-core scan and report

Figure 1: A pre-merge pipeline detects automatically testable accessibility regressions.

3. Install Playwright and axe-core

In your Astro project, install the test runner and accessibility integration:

npm install --save-dev @playwright/test @axe-core/playwright
npx playwright install chromium

For a Linux CI environment, the browser installation step will use --with-deps to install required system libraries. Keep your package-lock.json committed so CI can use npm ci reproducibly.

Check that package.json already contains Astro’s build and preview scripts. A typical static Astro project uses:

{
  "scripts": {
    "build": "astro build",
    "preview": "astro preview",
    "test:a11y": "playwright test tests/accessibility.spec.ts"
  }
}

Merge the test:a11y entry into your existing scripts rather than replacing the whole package.json. Preserve any current build commands or checks.

4. Configure a Browser Test Against the Astro Build

Create playwright.config.ts in the project root:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,
  retries: process.env.CI ? 1 : 0,
  reporter: [
    ['list'],
    ['html', { open: 'never' }],
  ],
  use: {
    baseURL: 'http://127.0.0.1:4321',
    trace: 'retain-on-failure',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
  ],
  webServer: {
    command: 'npm run preview -- --host 127.0.0.1 --port 4321',
    url: 'http://127.0.0.1:4321/',
    reuseExistingServer: !process.env.CI,
    timeout: 60_000,
  },
});

The webServer command assumes you’ve already run npm run build. It starts the preview of that build and lets Playwright stop the server afterward.

Important for Cloudflare Pages: astro preview is appropriate for checking statically generated pages. It may not reproduce production behavior of Cloudflare Pages Functions, edge middleware, or third-party integrations. Test those separately in a compatible environment.

5. Create Your First axe-core Test

Create tests/accessibility.spec.ts:

import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

const routes = ['/', '/blog/', '/contact/'];

for (const route of routes) {
  test(`accessibility scan: ${route}`, async ({ page }) => {
    const response = await page.goto(route);
    expect(response?.ok()).toBeTruthy();

    const results = await new AxeBuilder({ page })
      .withTags([
        'wcag2a',
        'wcag2aa',
        'wcag21a',
        'wcag21aa',
        'wcag22aa',
      ])
      .analyze();

    expect(results.violations).toEqual([]);
  });
}

The listed routes are examples for a blog with home, article index, and contact pages. Replace them with routes that actually exist in your project. The tag list limits the scan to certain WCAG A/AA-associated axe rules; it does not prove complete WCAG 2.2 AA conformance.

A failed assertion records that axe identified one or more violations on the rendered page. Investigate the report to determine the affected element, rule, and recommended remediation.

6. Run the Test Locally

Use two commands in sequence:

npm run build
npm run test:a11y

Playwright starts Astro’s preview server according to the configuration. After the run, open the HTML report:

npx playwright show-report

The default report is useful for locating the failing test and associated diagnostic output. It is not automatically a complete accessibility audit.

On Windows PowerShell, commands remain the same when npm resolves normally; if PowerShell’s execution policy blocks npm.ps1, you can use npm.cmd instead.

7. Understand Common axe-core Findings

Automated checks can detect many concrete issues, including missing names on controls, invalid ARIA references, duplicate IDs, and certain color-contrast problems. But they cannot reliably judge whether an image description conveys the right meaning or whether a multi-step interaction makes sense to a screen-reader user.

Finding Typical cause Better fix
Button has no accessible name Icon-only button without text Add meaningful text or aria-label
Form input has no label Placeholder used as the only label Add a visible <label> tied to the input
Color contrast issue Text and background colors too similar Adjust colors and retest
Invalid ARIA reference aria-labelledby points to missing ID Correct the relationship
Duplicate ID Component repeated with a fixed ID Generate unique IDs

Side-by-side guide showing what axe-core can detect automatically and what still requires manual accessibility testing

Figure 2: Automated rules are useful, but they do not replace human evaluation.

The Deque axe-core overview describes the engine and the accessibility standards it supports. Rules and WCAG tags can change between versions, so use your installed package’s rule set as the implementation reference.

8. Example: Fix an Unlabeled Search Button

An icon-only button may look understandable on screen while offering too little information to a screen reader:

<!-- Problematic: no useful accessible name -->
<button type="button">
  <svg aria-hidden="true" viewBox="0 0 24 24">...</svg>
</button>

A simple correction is:

<button type="button" aria-label="Open site search">
  <svg aria-hidden="true" viewBox="0 0 24 24">...</svg>
</button>

The label should describe the action, not repeat an icon’s visual appearance. Test the closed and opened states of search dialogs separately, including focus movement and keyboard dismissal.

9. Example: Test a Form After It Becomes Interactive

Axe scans the DOM at the moment you call .analyze(). If a form shows validation errors only after submission, scan the error state too.

import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

test('contact validation state is accessible', async ({ page }) => {
  await page.goto('/contact/');

  // Adapt selectors and behavior to your actual form.
  await page.getByRole('button', { name: /send/i }).click();
  await expect(page.getByText(/required/i).first()).toBeVisible();

  const results = await new AxeBuilder({ page }).analyze();
  expect(results.violations).toEqual([]);
});

This example assumes the form responds with visible validation errors before attempting to submit. A native HTML required constraint may instead block submission without creating the same error message, so adapt the test to your implementation.

Do not trigger real customer emails or production API calls during accessibility tests. Mock downstream requests or point to a dedicated testing environment when checking a live interactive form.

10. Add GitHub Actions

Create .github/workflows/accessibility.yml:

name: Accessibility tests

on:
  pull_request:
  workflow_dispatch:

permissions:
  contents: read

jobs:
  accessibility:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Build Astro
        run: npm run build

      - name: Install Chromium
        run: npx playwright install --with-deps chromium

      - name: Run accessibility tests
        run: npm run test:a11y

      - name: Upload test report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: accessibility-report
          path: |
            playwright-report/
            test-results/
          if-no-files-found: ignore
          retention-days: 7

The if: always() step preserves troubleshooting artifacts even if a test fails. For a repository with custom build output, private packages, or nonstandard scripts, adjust the workflow rather than assuming this configuration works unchanged.

GitHub Actions versions and supported Node.js releases evolve; check the maintained setup-node documentation before upgrading action majors.

11. Decide Which Pages to Scan

Scanning three routes is a useful start, but not sufficient coverage for every blog.

Prioritize a representative page from each distinct template and interaction type:

  • Home page and global navigation.
  • Blog index and article detail page.
  • Contact form, including validation states.
  • Search overlay or mobile navigation.
  • Cookie consent dialog and settings panel.
  • Any new interactive component or third-party widget.

Avoid an arbitrary list of thousands of pages in every pull request. Instead, test shared templates on each change and run broader route checks on a schedule if the site grows. A content change may still introduce a new issue, so include targeted testing for changed pages where practical.

A cookie banner can change the page’s accessible structure. Test its open state, accepted state, rejected state, and how focus returns after dismissal.

If analytics only loads after user consent, do not bypass that privacy behavior for the sake of the test. Set up separate scenarios for consent conditions.

Cloudflare Turnstile and embedded third-party controls may have their own loading conditions. When a preview environment does not host the real integration, clearly document the limitation and perform a targeted staging test instead of falsely reporting that production behavior was validated.

For background on a secure contact implementation, see How to Build a Secure Contact Form in Astro with Cloudflare Turnstile and Pages Functions.

13. Make Accessibility Reports Actionable

A test failure is only useful if the team can understand and resolve it. For every violation, record:

Field Why it matters
Route Which page was affected
Rule ID Which automated rule was triggered
Impact Approximate severity reported by axe
Element selector Where the affected element appears
Recommended fix What should change
Verification Evidence the issue no longer reproduces

Do not automatically suppress violations because they are inconvenient. If you must temporarily exclude a third-party element, document why, scope the exclusion narrowly, and keep a task to verify it another way.

14. Add Human Accessibility Checks

Automated checks cannot determine whether every interface is genuinely usable. Build a short manual routine into editorial or release reviews:

  1. Navigate with Tab and Shift+Tab only.
  2. Confirm focus indicators remain visible.
  3. Open and close menus, search dialogs, and modals using the keyboard.
  4. Check that focus does not become trapped unexpectedly.
  5. Use a screen reader to inspect meaningful labels and announcements.
  6. Zoom to 200% and inspect reflow on a narrow viewport.
  7. Review whether alternative text conveys the purpose of important images.

Pre-publish Astro accessibility checklist combining CI scanning and manual keyboard, focus and screen-reader review

Figure 3: A practical review combines repeatable automated gates with human testing.

If your site uses animated components, also evaluate motion and reduced-motion preferences. Choose testing approaches based on your actual users and the risk of an inaccessible interaction.

15. Common Mistakes

Mistake: Treating a Lighthouse score of 100 as proof of accessibility. Lighthouse audits only selected signals. A high score is encouraging, not a WCAG certificate.

Mistake: Scanning source files rather than rendered UI. Browser-level tests catch issues introduced by hydrated controls or the page’s final DOM.

Mistake: Testing only the homepage. A blog post template, search overlay, or contact form may behave differently.

Mistake: Skipping failed tests with exclusions. Exclusions hide problems unless deliberately scoped and reviewed.

Mistake: Running tests against production with destructive interactions. Prefer preview or staging, and mock side effects.

Mistake: Ignoring browser and tooling versions. Pin dependencies with a lockfile and update carefully.

16. Frequently Asked Questions

Can Playwright test Astro static sites?

Yes. Build the site and run the preview server. Playwright can then navigate to the rendered pages in Chromium, Firefox, or WebKit as configured.

Does axe-core guarantee WCAG compliance?

No. It catches automatically detectable issues under its rules. Manual testing and other forms of evaluation remain necessary.

Will accessibility tests slow down deployment?

They add test time, especially when installing browsers. Keep checks focused and use appropriate caching rather than disabling quality gates outright.

Should accessibility tests block every pull request?

Start by running them and reviewing failures. Once the tests are stable and the baseline issues are resolved, consider making the job a required check for important branches.

Can I test forms with Cloudflare Pages Functions using astro preview?

Not necessarily. The built Astro preview may not reproduce Cloudflare’s Functions runtime. For server-side form behavior, use a Cloudflare-compatible local or staging setup and test it separately.

Can I use this with Decap CMS?

Yes. The publishing workflow is separate from the browser test setup. You can scan the rendered article templates and, where suitable, add tests for the CMS interface in an authenticated test environment.

17. Production Readiness Checklist

  • Tests cover representative Astro page templates.
  • CI builds the actual site before scanning.
  • Browser versions and dependencies are reproducible.
  • Test reports remain accessible after failure.
  • Form and modal interactive states receive targeted checks.
  • Tests do not send real mail or modify live records.
  • Cookie consent behavior is preserved.
  • Keyboard focus and screen reader behavior receive human review.
  • Accessibility defects are assigned and retested.
  • Exceptions are narrowly scoped and documented.

18. Final Thoughts

A fast website is not automatically an accessible one. Automated accessibility testing brings repeatability to your Astro development process, but the strongest workflow also checks real interactions with human judgment.

For small blogs, start with a few representative pages, a dependable Playwright configuration, and a GitHub Actions report. Expand coverage as you introduce new components and editorial features.

The goal is not a perfect dashboard score. It is a website people can actually use.

Continue Reading

Official Technical References

Technical disclosure: This article contains illustrative code and an example CI pipeline. It has not been executed against the source repository of DuongHoangNam.com; deployment readiness requires testing the actual project’s scripts, components, and Cloudflare setup.

About the Author

Duong Hoang Nam

Duong Hoang Nam

Software engineer sharing practical tutorials, real-world experiments, and insights on AI tools, automation, and web development.

Read My Story →

Related Articles