refactor playwright service class

This commit is contained in:
Aarish
2025-05-23 00:42:55 -05:00
parent b194ff6924
commit 7773e85811

View File

@@ -1,10 +1,14 @@
// import playwright dependencies // import playwright dependencies
const { test, expect } = require('../helpers/axe-test.js');
const { chromium } = require('playwright'); const { chromium } = require('playwright');
const { injectAxe, checkA11y } = require('axe-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 { class PlaywrightService {
#domain; // domain of the site to be tested #domain; // domain of the site to be tested
@@ -21,7 +25,7 @@ class PlaywrightService {
// get the url of the site to be tested // get the url of the site to be tested
rootUrl() { rootUrl() {
return `https://${domain}`; return `https://${this.#domain}`;
} }
/** /**
@@ -32,28 +36,73 @@ class PlaywrightService {
* *
* @returns {Array} - The list of urls to be tested * @returns {Array} - The list of urls to be tested
*/ */
async runAccessibilityTest() { async getUrlList() {
const browser = await chromium.launch(); const browser = await chromium.launch();
const page = await browser.newPage(); const page = await browser.newPage();
let urls = [];
try { try {
await page.goto(this.rootUrl()); await page.goto(this.sitemapUrl());
await injectAxe(page); const content = await page.content();
const results = await page.evaluate(async () => { const dom = new jsdom.JSDOM(content);
return await window.axe.run(); const sitemapUrls = dom.window.document.querySelectorAll('a[href]');
}); urls = Array.from(sitemapUrls).map(link => link.href);
return results.violations; console.log('Sitemap URLs:', urls);
} catch (error) {
console.error('Error fetching sitemap:', error);
} finally { } finally {
await browser.close(); await browser.close();
} }
return urls;
}
/**
*
* @param {*} url
* @returns
*/
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; return results;
} }
/**
* Run accessibility test on given url
*
* @param {string} url - The URL of the page to test
* // TODO: Queue all urls from sitemap
*/
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';
}
/** /**
* *
*/ */