-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathindex.js
392 lines (339 loc) · 12.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/* Event listeners + custom commands for Cypress */
const browserStackLog = (message) => {
if (!Cypress.env('BROWSERSTACK_LOGS')) return;
cy.task('browserstack_log', message);
}
const sendToReporter = (data) => {
cy.task('test_accessibility_data', data);
}
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 performScan = (win, payloadToSend) =>
new Promise(async (resolve, reject) => {
const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
if (!isHttpOrHttps) {
resolve();
}
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 30, retryInterval = 100) {
return new Promise(async (resolve, reject) => {
let count = 0;
const intervalID = setInterval(async () => {
if (count > retryCount) {
clearInterval(intervalID);
reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function startScan() {
function onScanComplete() {
win.removeEventListener("A11Y_SCAN_FINISHED", onScanComplete);
resolve();
}
win.addEventListener("A11Y_SCAN_FINISHED", onScanComplete);
const e = new CustomEvent("A11Y_SCAN", { detail: payloadToSend });
win.dispatchEvent(e);
}
if (findAccessibilityAutomationElement()) {
startScan();
} else {
waitForScannerReadiness()
.then(startScan)
.catch(async (err) => {
resolve("Scanner is not ready on the page after multiple retries. performscan");
});
}
})
const getAccessibilityResultsSummary = (win) =>
new Promise((resolve) => {
const isHttpOrHttps = /^(http|https):$/.test(window.location.protocol);
if (!isHttpOrHttps) {
resolve();
}
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 30, retryInterval = 100) {
return new Promise((resolve, reject) => {
let count = 0;
const intervalID = setInterval(() => {
if (count > retryCount) {
clearInterval(intervalID);
reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function getSummary() {
function onReceiveSummary(event) {
win.removeEventListener("A11Y_RESULTS_SUMMARY", onReceiveSummary);
resolve(event.detail);
}
win.addEventListener("A11Y_RESULTS_SUMMARY", onReceiveSummary);
const e = new CustomEvent("A11Y_GET_RESULTS_SUMMARY");
win.dispatchEvent(e);
}
if (findAccessibilityAutomationElement()) {
getSummary();
} else {
waitForScannerReadiness()
.then(getSummary)
.catch((err) => {
resolve();
});
}
})
const getAccessibilityResults = (win) =>
new Promise((resolve) => {
const isHttpOrHttps = /^(http|https):$/.test(window.location.protocol);
if (!isHttpOrHttps) {
resolve();
}
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 30, retryInterval = 100) {
return new Promise((resolve, reject) => {
let count = 0;
const intervalID = setInterval(() => {
if (count > retryCount) {
clearInterval(intervalID);
reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function getResults() {
function onReceivedResult(event) {
win.removeEventListener("A11Y_RESULTS_RESPONSE", onReceivedResult);
resolve(event.detail);
}
win.addEventListener("A11Y_RESULTS_RESPONSE", onReceivedResult);
const e = new CustomEvent("A11Y_GET_RESULTS");
win.dispatchEvent(e);
}
if (findAccessibilityAutomationElement()) {
getResults();
} else {
waitForScannerReadiness()
.then(getResults)
.catch((err) => {
resolve();
});
}
});
const saveTestResults = (win, payloadToSend) =>
new Promise( (resolve, reject) => {
try {
const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
if (!isHttpOrHttps) {
resolve("Unable to save accessibility results, Invalid URL.");
}
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 30, retryInterval = 100) {
return new Promise((resolve, reject) => {
let count = 0;
const intervalID = setInterval(async () => {
if (count > retryCount) {
clearInterval(intervalID);
reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function saveResults() {
function onResultsSaved(event) {
resolve();
}
win.addEventListener("A11Y_RESULTS_SAVED", onResultsSaved);
const e = new CustomEvent("A11Y_SAVE_RESULTS", {
detail: payloadToSend,
});
win.dispatchEvent(e);
}
if (findAccessibilityAutomationElement()) {
saveResults();
} else {
waitForScannerReadiness()
.then(saveResults)
.catch(async (err) => {
resolve("Scanner is not ready on the page after multiple retries. after run");
});
}
} catch(er) {
resolve()
}
})
const shouldScanForAccessibility = (attributes) => {
if (Cypress.env("IS_ACCESSIBILITY_EXTENSION_LOADED") !== "true") return false;
const extensionPath = Cypress.env("ACCESSIBILITY_EXTENSION_PATH");
const isHeaded = Cypress.browser.isHeaded;
if (!isHeaded || (extensionPath === undefined)) return false;
let shouldScanTestForAccessibility = true;
if (Cypress.env("INCLUDE_TAGS_FOR_ACCESSIBILITY") || Cypress.env("EXCLUDE_TAGS_FOR_ACCESSIBILITY")) {
try {
let includeTagArray = [];
let excludeTagArray = [];
if (Cypress.env("INCLUDE_TAGS_FOR_ACCESSIBILITY")) {
includeTagArray = Cypress.env("INCLUDE_TAGS_FOR_ACCESSIBILITY").split(";")
}
if (Cypress.env("EXCLUDE_TAGS_FOR_ACCESSIBILITY")) {
excludeTagArray = Cypress.env("EXCLUDE_TAGS_FOR_ACCESSIBILITY").split(";")
}
browserStackLog("EXCLUDE_TAGS_FOR_ACCESSIBILITY = " + excludeTagArray)
browserStackLog("INCLUDE_TAGS_FOR_ACCESSIBILITY = " + includeTagArray)
const fullTestName = attributes.title;
browserStackLog("fullTestName = " + fullTestName)
const excluded = excludeTagArray.some((exclude) => fullTestName.includes(exclude));
const included = includeTagArray.length === 0 || includeTags.some((include) => fullTestName.includes(include));
shouldScanTestForAccessibility = !excluded && included;
} catch (error) {
browserStackLog("Error while validating test case for accessibility before scanning. Error : ", error);
}
}
return shouldScanTestForAccessibility;
}
Cypress.on('command:start', async (command) => {
if(!command || !command.attributes) return;
if(command.attributes.name == 'window' || command.attributes.name == 'then' || command.attributes.name == 'wrap') {
return;
}
if (!commandsToWrap.includes(command.attributes.name)) return;
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
let shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
sendToReporter({[attributes.title]: shouldScanTestForAccessibility})
if (!shouldScanTestForAccessibility) return;
cy.window().then((win) => {
browserStackLog('Performing scan form command ' + command.attributes.name);
cy.wrap(performScan(win, {method: command.attributes.name}), {timeout: 30000});
})
})
afterEach(() => {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest;
cy.task('readFileMaybe', 'testDetails.json').then(data => {
browserStackLog('FILE CONTENT ::::: ' + data)
if (data === null) return;
let testDetails = {}
try {
testDetails = JSON.parse(data);
} catch (err) {
browserStackLog('Error while parsing json for testDetails:' + err)
}
const testId = testDetails[attributes.fullTitle()]
browserStackLog('TestId : ' + testId)
cy.window().then(async (win) => {
let shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
sendToReporter({[attributes.title]: shouldScanTestForAccessibility})
if (!shouldScanTestForAccessibility) return cy.wrap({});
cy.wrap(performScan(win), {timeout: 30000}).then(() => {
try {
let os_data;
if (Cypress.env("OS")) {
os_data = Cypress.env("OS");
} else {
os_data = Cypress.platform === 'linux' ? 'mac' : "win"
}
let filePath = '';
if (attributes.invocationDetails !== undefined && attributes.invocationDetails.relativeFile !== undefined) {
filePath = attributes.invocationDetails.relativeFile;
}
const payloadToSend = {
'thTestRunUuid': testId,
'thBuildUuid': Cypress.env("BROWSERSTACK_TESTHUB_UUID"),
'thJwtToken': Cypress.env('BROWSERSTACK_TESTHUB_JWT')
};
browserStackLog(`Saving accessibility test results`);
cy.wrap(saveTestResults(win, payloadToSend), {timeout: 30000}).then(() => {
browserStackLog(`Saved accessibility test results`);
})
} catch (er) {
}
})
})
});
})
Cypress.Commands.add('performScan', () => {
try {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
const shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
if (!shouldScanTestForAccessibility) {
browserStackLog(`Not a Accessibility Automation session, cannot perform scan.`);
return cy.wrap({});
}
cy.window().then(async (win) => {
browserStackLog(`Performing accessibility scan`);
await performScan(win);
});
} catch {}
})
Cypress.Commands.add('getAccessibilityResultsSummary', () => {
try {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
const shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
if (!shouldScanTestForAccessibility) {
browserStackLog(`Not a Accessibility Automation session, cannot retrieve Accessibility results summary.`);
return cy.wrap({});
}
cy.window().then(async (win) => {
await performScan(win);
browserStackLog('Getting accessibility results summary');
return await getAccessibilityResultsSummary(win);
});
} catch {}
});
Cypress.Commands.add('getAccessibilityResults', () => {
try {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
const shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
if (!shouldScanTestForAccessibility) {
browserStackLog(`Not a Accessibility Automation session, cannot retrieve Accessibility results.`);
return cy.wrap({});
}
/* browserstack_accessibility_automation_script */
cy.window().then(async (win) => {
await performScan(win);
browserStackLog('Getting accessibility results');
return await getAccessibilityResults(win);
});
} catch {}
});