Skip to content

AT-281-OverwriteCommands #355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
241 changes: 82 additions & 159 deletions accessibility/scanner/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,192 +4,115 @@ const LambdatestLog = (message) => {
cy.task('lambdatest_log', message);
}

const commandsToWrap = ['visit', 'click', 'type', 'request', 'dblclick', 'rightclick', 'clear', 'check', 'uncheck', 'select', 'trigger', 'selectFile', 'scrollIntoView', 'scroll', 'scrollTo', 'blur', 'focus', 'go', 'reload', 'submit', 'viewport', 'origin'];
const commandsToOverride = [
'visit', 'click', 'type', 'request', 'dblclick', 'rightclick', 'clear', 'check',
'uncheck', 'select', 'trigger', 'selectFile', 'scrollIntoView', 'scrollTo',
'blur', 'focus', 'go', 'reload', 'submit', 'viewport', 'origin'
];

let currentWindow = null;
Cypress.Commands.add('storeWindowObject', () => {
cy.window().then(win => {
currentWindow = win;
});
});

const setScanConfig = (win, payload) =>
new Promise(async (resolve, reject) => {
beforeEach(() => {
cy.storeWindowObject();
});

const setScanConfig = (win, payload) => {
return new Promise((resolve, reject) => {
const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
if (!isHttpOrHttps) {
resolve();
}
if (!isHttpOrHttps) return resolve();

console.log('log', "Accessibility setting scan config");

function startScan() {
console.log('log', "Accessibility setting scan config")
function onScanComplete(event) {
win.document.removeEventListener("automation-custom-event", onScanComplete);
console.log('log', "Recieved scan config data " + event.detail)
resolve(event.detail);
win.document.removeEventListener("automation-custom-event", onScanComplete);
console.log('log', "Received scan config data: ", event.detail);
resolve(event.detail);
}
win.document.addEventListener("automation-custom-event", onScanComplete);

win.document.addEventListener("automation-custom-event", onScanComplete);
const e = new CustomEvent("accessibility-extension-custom-event", { detail: payload });
win.document.dispatchEvent(e);


setTimeout(() => {
resolve(new Error('automation-custom-event not received within timeout'));
}, 45000);
}
startScan();

})

const getScanData = (win, payload) =>
new Promise( async (resolve,reject) => {
const isHttpOrHttps = /^(http|https):$/.test(window.location.protocol);
if (!isHttpOrHttps) {
resolve();
}


function getSummary() {
setTimeout(() => {
reject(new Error('automation-custom-event not received within timeout'));
}, 45000);
});
};

const getScanData = (win, payload) => {
return new Promise((resolve, reject) => {
const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
if (!isHttpOrHttps) return resolve();

function onReceiveSummary(event) {

win.document.removeEventListener("automation-custom-event", onReceiveSummary);
resolve(event.detail);
win.document.removeEventListener("automation-custom-event", onReceiveSummary);
resolve(event.detail);
}



win.document.addEventListener("automation-custom-event", onReceiveSummary);
const e = new CustomEvent("accessibility-extension-custom-event", { detail: payload });
win.document.dispatchEvent(e);

setTimeout(() => {
resolve(new Error('automation-custom-event not received within timeout'));
resolve(new Error('automation-custom-event not received within timeout'));
}, 45000);

}


getSummary();

})

function processAccessibilityReport(win){
let wcagCriteriaValue = Cypress.env("WCAG_CRITERIA") || "wcag21a";
let bestPracticeValue = Cypress.env("BEST_PRACTICE") || false;
let needsReviewValue = Cypress.env("NEEDS_REVIEW") || true;
bestPracticeValue = bestPracticeValue == "true" ? true : false;
needsReviewValue = needsReviewValue == "true" ? true : false;
const payloadToSend = {
message: 'SET_CONFIG',
wcagCriteria: wcagCriteriaValue,
bestPractice: bestPracticeValue,
needsReview: needsReviewValue
}

console.log('log', "payload to send " + payloadToSend);
let testId = Cypress.env("TEST_ID") || ""

const filePath = Cypress.env("ACCESSIBILITY_REPORT_PATH") || 'cypress/results/accessibilityReport_' + testId + '.json';

cy.wrap(setScanConfig(win, payloadToSend), {timeout: 30000}).then((res) => {
console.log('logging config reponse', res);

const payload = {
message: 'GET_LATEST_SCAN_DATA',
}

cy.wrap(getScanData(win, payload), {timeout: 45000}).then((res) => {
LambdatestLog('log', "scanning data ");


cy.task('initializeFile', filePath).then((filePath) => {
cy.task('readFileIfExists', filePath,{ log: true, timeout: 45000 }).then((result) => {
let resultsArray = [{}];
console.log('logging report', res);
// If the file is not empty, parse the existing content
if (result.exists && result.content) {
try {
resultsArray = JSON.parse(result.content);
} catch (e) {
console.log("parsing error for content " , result.content)
console.log('Error parsing JSON file:', e);
return;
}
} else if(!result.exists) {
console.log('accessibility file does not exist');
}
if (res) {
console.log('scanned data recieved is', res.message);
});
};

async function processAccessibilityReport(url) {
try {
let wcagCriteriaValue = Cypress.env("WCAG_CRITERIA") || "wcag21a";
let bestPracticeValue = Cypress.env("BEST_PRACTICE") === "true";
let needsReviewValue = Cypress.env("NEEDS_REVIEW") !== "false"; // Default to true

const payloadToSend = {
message: 'SET_CONFIG',
wcagCriteria: wcagCriteriaValue,
bestPractice: bestPracticeValue,
needsReview: needsReviewValue
};

console.log('log', "Payload to send: for url: ", payloadToSend,url);
try {
let setResult = await setScanConfig(currentWindow, payloadToSend);
console.log('SET SCAN response:', setResult);
} catch (err) {
console.error("Error while setting scan", err);
}

if (res && res.message == "GET_LATEST_SCAN_DATA") {
try {
// Append the new result
resultsArray.push(res);
console.log('resultsarray logging', resultsArray);
} catch (e) {
console.log('Error pushing issues to array:', e);
}
let scanData;
try {
const payload = {message: 'GET_LATEST_SCAN_DATA'};
scanData = await getScanData(currentWindow, payload);
LambdatestLog("LambdaTest Accessibility: Scanning URL");
} catch (err) {
console.error("GET SCAN:Error while setting scan", err);
}

// Write the updated content back to the file
cy.writeFile(filePath, resultsArray, { log: true, timeout: 45000 });
});
});
});
console.log("Logging response before sending to API:", scanData);

});
} catch (error) {
LambdatestLog("ERROR", error);
}
}

Cypress.on('command:start', async (command) => {
if(!command || !command.attributes) return;
if(command.attributes.name == 'window' || command.attributes.name == 'then' || command.attributes.name == 'wrap' || command.attributes.name == 'wait') {
return;
}

if (!commandsToWrap.includes(command.attributes.name)) return;
let isAccessibilityLoaded = Cypress.env("ACCESSIBILITY") || false;
if (!isAccessibilityLoaded){
console.log('log', "accessibility not enabled " + isAccessibilityLoaded);
return;
}


console.log('log', "debugging scan form command " + command.attributes.name);

cy.window().then((win) => {
processAccessibilityReport(win);
});
})

// Ensure scan runs AFTER visit completes
Cypress.Commands.overwrite('visit', (originalFn, url, options) => {
function getReportAfterVisiting() {
originalFn(url, options)
commandsToOverride.forEach((command) => {
Cypress.Commands.overwrite(command, (originalFn, url, options) => {
let isAccessibilityLoaded = Cypress.env("ACCESSIBILITY") || false;
if (!isAccessibilityLoaded) {
console.log('log', "Accessibility not enabled.");
return;
return originalFn(url, options);
}

cy.window().then((win) => {
console.log('log', "Running accessibility scan after visit: " + url);
processAccessibilityReport(win);
});
}

return getReportAfterVisiting();
});


Cypress.on('command:end', (command) => {

return;
})

return originalFn(url, options).then(() => {
processAccessibilityReport(url);
})

afterEach(() => {
console.log("after each hook")
let isAccessibilityLoaded = Cypress.env("ACCESSIBILITY") || false;
if (!isAccessibilityLoaded){
console.log('log', "accessibility not enabled " + isAccessibilityLoaded);
return;
}
cy.window().then((win) => {
processAccessibilityReport(win);
})


})
});
});