Writing Tests for axe DevTools HTML for Playwright

Link to Writing Tests for axe DevTools HTML for Playwright copied to clipboard

How to write effective tests for accessibility using axe DevTools HTML for Playwright

Writing tests with axe DevTools

Producing accessibility scan results with axe DevTools can be as easy as one line of code. These results can be consumed raw, used in conjunction with an assertion library, or used to create accessibility reports.

Prerequisites

In order to test pages with axe DevTools, you first need it imported and initialized in your project. If you haven't completed this step yet, view this guide on how to do it.

Getting Scan Context

Before you can scan a page for accessibility, it needs to be accessed by Playwright.

//Launch the Playwright Driver
const browser = await playwright.chromium.launch();
//Create a new browser context
const context = await browser.newContext();
//Create a new page in the browser
const page = await context.newPage();
//Send the browser to the desired page to scan
await page.goto('$URL');

Bypassing Content Security Policy

If the page you are trying to scan has Content Security Policy enabled, you may have issues. If you encounter this problem, axe DevTools includes a workaround. Simply include this statement after your page is created:

await context = await browser.newContext({ bypassCSP: true })

Once Playwright has accessed the page, you can scan it with axe DevTools and save the results. The most simple way to view the results of the scan is to console log the results object.

const results = await new AxeDevtoolsBuilder({ page }).analyze();
console.log(results);

Complete Sample File

const playwright = require('playwright');
const AxeDevtoolsBuilder = require('@axe-devtools/playwright').default;

(async () => {

    //Launch the Playwright Driver
    const browser = await playwright.chromium.launch();
    //Create a new browser context
    const context = await browser.newContext();
    //Create a new page in the browser
    const page = await context.newPage();

    //launch page for testing (has intentional accessibility issues)
    await page.goto('https://broken-workshop.dequelabs.com');

    //analyze page
    const results = await new AxeDevtoolsBuilder({ page }).analyze();
    
    //log results
    console.log(results);

    //close webdriver
    browser.close();
})();

Next Steps

Now that you've successfully completed an accessibility scan, you're ready to move on to more advanced scanning topics like generating reports and using the results object.

Troubleshooting

If you have trouble with getting scan results, contact your Deque representative directly, reach us via our support desk, or send us an email. We'll be happy to help.