Files
Playwright-A11y-Dashboard/services/PlaywrightService.js
2025-05-23 00:55:04 -05:00

110 lines
3.0 KiB
JavaScript

// import playwright dependencies
const { chromium } = require('playwright');
const { injectAxe, checkA11y } = require('axe-playwright');
const jsdom = require("jsdom");
/**
* PlaywrightService class
*
* This class is used to interact with the Playwright library
*/
class PlaywrightService {
#domain; // domain of the site to be tested
// constructor
constructor(domain) {
this.#domain = domain;
}
// get sitemap url for the this domain
sitemapUrl() {
return `${this.rootUrl()}/sitemap.xml`;
}
// get the url of the site to be tested
rootUrl() {
return `https://${this.#domain}`;
}
/**
* Get the list of urls to be tested by querying
* the sitemap and returning the list of urls
*
* @param {string} url - The URL of the sitemap
*
* @returns {Array} - The list of urls to be tested
*/
async getUrlList() {
const browser = await chromium.launch();
const page = await browser.newPage();
let urls = [];
try {
await page.goto(this.sitemapUrl());
const content = await page.content();
const dom = new jsdom.JSDOM(content);
const sitemapUrls = dom.window.document.querySelectorAll('a[href]');
urls = Array.from(sitemapUrls).map(link => link.href);
console.log('Sitemap URLs:', urls);
} catch (error) {
console.error('Error fetching sitemap:', error);
} finally {
await browser.close();
}
return urls;
}
/**
* Loops through the list of urls and runs the
* accessibility test on each url
*
* @returns {Array} - The list of results from the accessibility test
*/
async getAccessibilityResults() {
const urls = await this.getUrlList();
let results = [];
while (urls.length > 0) {
const url = urls.pop();
console.log('Running accessibility test on:', url);
const result = await PlaywrightService.#runAccessibilityTest(url);
results.push([url, result]);
}
return results;
}
/**
* Run accessibility test on given url
*
* @param {string} url - The URL of the page to test
*
* @returns {Array} - The list of results from the accessibility test
*/
static async #runAccessibilityTest(url) {
const browser = await chromium.launch();
const page = await browser.newPage();
let results = [];
try {
await page.goto(url);
await injectAxe(page);
results = await page.evaluate(async () => {
return await window.axe.run();
});
} catch(error) {
console.error('Error running accessibility test:', error);
} finally {
await browser.close();
}
return results?.violations || 'No violations found';
}
}
module.exports = PlaywrightService;