forked from dequelabs/axe-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testutils.js
711 lines (650 loc) · 21.2 KB
/
testutils.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
/*eslint no-unused-vars: 0*/
// these are global to the entire test suite so need to be declared at the global
// level (old architecture that should not be relied on in any new code)
var checks;
var commons;
(() => {
// Let the user know they need to disable their axe/attest extension before running the tests.
if (window.__AXE_EXTENSION__) {
throw new Error(
'You must disable your axe/attest browser extension in order to run the test suite.'
);
}
const testUtils = (axe.testUtils = {});
const originalChecks = (checks = axe._audit.checks);
const originalAudit = axe._audit;
const originalRules = axe._audit.rules;
const originalCommons = (commons = axe.commons);
// Global chai configuration
if (window.chai) {
window.chai.config.truncateThreshold = 0;
}
// add fixture to the body if it's not already
let fixture = document.getElementById('fixture');
if (!fixture) {
fixture = document.createElement('div');
fixture.setAttribute('id', 'fixture');
document.body.insertBefore(fixture, document.body.firstChild);
}
// determine which checks are used only in the `none` array of rules
const noneChecks = [];
function verifyIsNoneCheck(check) {
const index = noneChecks.indexOf(check);
if (index !== -1) {
noneChecks.splice(index, 1);
}
}
axe._audit.rules.forEach(function (rule) {
rule.none.forEach(function (check) {
check = check.id || check;
if (noneChecks.indexOf(check) === -1) {
noneChecks.push(check);
}
});
});
axe._audit.rules.forEach(function (rule) {
rule.any.forEach(verifyIsNoneCheck);
rule.all.forEach(verifyIsNoneCheck);
});
/**
* Create a check context for mocking/resetting data and relatedNodes in tests
*
* @return Object
*/
testUtils.MockCheckContext = function () {
'use strict';
return {
_relatedNodes: [],
_data: null,
// When using this.async() in a check, assign a function to _onAsync
// to catch the response.
_onAsync: null,
async: function () {
const self = this;
return function (result) {
// throws if _onAsync isn't set
self._onAsync(result, self);
};
},
data: function (d) {
this._data = d;
},
relatedNodes: function (nodes) {
this._relatedNodes = Array.isArray(nodes) ? nodes : [nodes];
},
reset: function () {
this._data = null;
this._relatedNodes = [];
this._onAsync = null;
}
};
};
/**
* Provide an API for determining Shadow DOM v0 and v1 support in tests.
*
* @param HTMLDocumentElement The document of the current context
* @return Object
*/
testUtils.shadowSupport = (function (document) {
'use strict';
const v0 =
document.body && typeof document.body.createShadowRoot === 'function',
v1 = document.body && typeof document.body.attachShadow === 'function';
return {
v0: v0 === true,
v1: v1 === true,
undefined:
document.body &&
typeof document.body.attachShadow === 'undefined' &&
typeof document.body.createShadowRoot === 'undefined'
};
})(document);
/**
* Return the fixture element
* @return HTMLElement
*/
testUtils.getFixture = function () {
'use strict';
return fixture;
};
/**
* Method for injecting content into a fixture
* @param {String|Node} content Stuff to go into the fixture (html or DOM node)
* @return HTMLElement
*/
testUtils.injectIntoFixture = function (content) {
'use strict';
if (typeof content !== 'undefined') {
fixture.innerHTML = '';
}
if (typeof content === 'string') {
fixture.innerHTML = content;
} else if (content instanceof Node) {
fixture.appendChild(content);
} else if (Array.isArray(content)) {
content.forEach(function (node) {
fixture.appendChild(node);
});
}
return fixture;
};
/**
* Method for injecting content into a fixture and caching
* the flattened DOM tree (light and Shadow DOM together)
*
* @param {String|Node} content Stuff to go into the fixture (html or DOM node)
* @return HTMLElement
*/
testUtils.fixtureSetup = function (content) {
'use strict';
testUtils.injectIntoFixture(content);
axe.teardown();
return axe.setup(fixture);
};
/**
* Create check arguments
*
* @param Node|String Stuff to go into the fixture (html or node)
* @param Object Options argument for the check (optional, default: {})
* @param String Target for the check, CSS selector (default: '#target')
* @return Array
*/
testUtils.checkSetup = function (content, options, target) {
'use strict';
// Normalize the params
if (typeof options !== 'object') {
target = options;
options = {};
}
// Normalize target, allow it to be the inserted node or '#target'
target = target || (content instanceof Node ? content : '#target');
const rootNode = testUtils.fixtureSetup(content);
let node;
if (typeof target === 'string') {
node = axe.utils.querySelectorAll(rootNode, target)[0];
} else if (target instanceof Node) {
node = axe.utils.getNodeFromTree(target);
} else {
node = target;
}
return [node.actualNode, options, node];
};
/**
* Create a shadow DOM tree on #shadow and setup axe for it, returning #target
*
* @param Node|String Stuff to go into the fixture (html string or DOM Node)
* @param Node|String Stuff to go into the shadow boundary (html or node)
* @param String Target selector for the check, can be inside or outside of Shadow DOM (optional, default: '#target')
* @return VirtualNode
*/
testUtils.queryShadowFixture = function (
content,
shadowContent,
targetSelector
) {
'use strict';
// Normalize target, allow it to be the provided string or use '#target' to query composed tree
if (typeof targetSelector !== 'string') {
targetSelector = '#target';
}
const fixtureNode = testUtils.injectIntoFixture(content);
let targetCandidate = fixtureNode.querySelector(targetSelector);
let container = targetCandidate;
if (!targetCandidate) {
// check if content specifies a shadow container
container = fixtureNode.querySelector('#shadow');
if (!container) {
container = fixtureNode.firstChild;
}
}
// attach a shadowRoot with the content provided
const shadowRoot = container.attachShadow({ mode: 'open' });
if (typeof shadowContent === 'string') {
shadowRoot.innerHTML = shadowContent;
} else if (content instanceof Node) {
shadowRoot.appendChild(shadowContent);
}
if (!targetCandidate) {
targetCandidate = shadowRoot.querySelector(targetSelector);
}
if (!targetSelector && !targetCandidate) {
throw 'shadowCheckSetup requires at least one fragment to have #target, or a provided targetSelector';
}
// query the composed tree AFTER shadowDOM has been attached
axe.setup(fixtureNode);
return axe.utils.getNodeFromTree(targetCandidate);
};
/**
* Create check arguments with Shadow DOM. Target can be inside or outside of Shadow DOM, queried by
* adding `id="target"` to a fragment. Or specify a custom selector as the `targetSelector` argument.
*
* @param Node|String Stuff to go into the fixture (html string or DOM Node)
* @param Node|String Stuff to go into the shadow boundary (html or node)
* @param Object Options argument for the check (optional, default: {})
* @param String Target selector for the check, can be inside or outside of Shadow DOM (optional, default: '#target')
* @return Array
*/
testUtils.shadowCheckSetup = function (
content,
shadowContent,
options,
targetSelector
) {
// Normalize the object params
if (typeof options !== 'object') {
options = {};
}
const node = testUtils.queryShadowFixture(
content,
shadowContent,
targetSelector
);
return [node.actualNode, options, node];
};
/**
* Setup axe._tree flat tree
* @param Node Stuff to go in the flat tree
* @returns vNode[]
*/
testUtils.flatTreeSetup = function (content) {
axe._tree = axe.utils.getFlattenedTree(content);
return axe._tree;
};
/**
* Wait for all nested frames to be loaded
*
* @param Object Window to wait for (optional)
* @param function Callback, called once resolved
* @param function Callback, called once rejected
*/
testUtils.awaitNestedLoad = function awaitNestedLoad(win, cb, errCb) {
'use strict';
if (typeof win === 'function') {
errCb = cb;
cb = win;
win = window;
}
const document = win.document;
const q = axe.utils.queue();
// Wait for page load
q.defer(function (resolve) {
if (document.readyState === 'complete') {
resolve();
} else {
win.addEventListener('load', resolve);
}
});
// Wait for all frames to be loaded
Array.from(document.querySelectorAll('iframe')).forEach(function (frame) {
q.defer(function (resolve) {
return awaitNestedLoad(frame.contentWindow, resolve);
});
});
// Complete (don't pass the args on to the callback)
q.then(function () {
cb();
});
if (errCb) {
q.catch(errCb);
}
};
/**
* Add a given stylesheet dynamically to the document
*
* @param {Object} data composite object containing properties to create stylesheet
* @property {String} data.href relative or absolute url for stylesheet to be loaded
* @property {Boolean} data.mediaPrint boolean to represent if the constructed sheet is for print media
* @property {String} data.text text contents to be written to the stylesheet
* @property {String} data.id id reference to link or style to be added to document
* @param {Object} rootNode document/fragment to which to append style
* @returns {Object} axe.utils.queue
*/
testUtils.addStyleSheet = function addStyleSheet(data, rootNode) {
const doc = rootNode ? rootNode : document;
const q = axe.utils.queue();
if (data.href) {
q.defer(function (resolve, reject) {
const link = doc.createElement('link');
link.rel = 'stylesheet';
link.href = data.href;
if (data.id) {
link.id = data.id;
}
if (data.mediaPrint) {
link.media = 'print';
}
link.onload = function () {
setTimeout(function () {
resolve();
});
};
link.onerror = function () {
reject();
};
doc.head.appendChild(link);
});
} else {
q.defer(function (resolve) {
const style = doc.createElement('style');
if (data.id) {
style.id = data.id;
}
style.type = 'text/css';
style.appendChild(doc.createTextNode(data.text));
doc.head.appendChild(style);
setTimeout(function () {
resolve();
}, 100); // -> note: gives firefox to load (document.stylesheets), other browsers are fine.
});
}
return q;
};
/**
* Add a list of stylesheets
*
* @param {Object} sheets array of sheets data object
* @returns {Object} axe.utils.queue
*/
testUtils.addStyleSheets = function addStyleSheets(sheets, rootNode) {
const q = axe.utils.queue();
sheets.forEach(function (data) {
q.defer(axe.testUtils.addStyleSheet(data, rootNode));
});
return q;
};
/**
* Remove a list of stylesheets from the document
* @param {Array<Object>} sheets array of sheets data object
* @returns {Object} axe.utils.queue
*/
testUtils.removeStyleSheets = function removeStyleSheets(sheets) {
const q = axe.utils.queue();
sheets.forEach(function (data) {
q.defer(function (resolve, reject) {
const node = document.getElementById(data.id);
if (!node || !node.parentNode) {
reject();
}
node.parentNode.removeChild(node);
resolve();
});
});
return q;
};
/**
* Assert a given stylesheet against selectorText and cssText
*
* @param {Object} sheet CSS Stylesheet
* @param {String} selectorText CSS Selector
* @param {String} cssText CSS Values
* @param {Boolean} includes (Optional) flag to check if existence of selectorText within cssText
*/
testUtils.assertStylesheet = function assertStylesheet(
sheet,
selectorText,
cssText,
includes
) {
assert.isDefined(sheet);
assert.property(sheet, 'cssRules');
if (includes) {
assert.isTrue(cssText.includes(selectorText));
} else {
assert.equal(sheet.cssRules[0].selectorText, selectorText);
// compare the selector properties
const styleEl = document.createElement('style');
styleEl.type = 'text/css';
styleEl.innerHTML = cssText;
document.body.appendChild(styleEl);
const testSheet = document.styleSheets[document.styleSheets.length - 1];
const sheetRule = sheet.cssRules[0];
const testRule = testSheet.cssRules[0];
try {
for (let i = 0; i < testRule.style.length; i++) {
const property = testRule.style[i];
assert.equal(sheetRule.style[property], testRule.style[property]);
}
} finally {
styleEl.parentNode.removeChild(styleEl);
}
}
};
/**
* Injecting content into a fixture and return queried element within fixture
*
* @param {String|Node} html - content to go into the fixture (html or DOM node)
* @param {String} [query=#target] - the CSS selector query to find target DOM node
* @return {VirtualNode}
*/
testUtils.queryFixture = function queryFixture(html, query) {
query = query || '#target';
const rootNode = testUtils.fixtureSetup(html);
const vNode = axe.utils.querySelectorAll(rootNode, query)[0];
assert.exists(
vNode,
'Node does not exist in query `' +
query +
'`. This is usually fixed by adding the default target (`id="target"`) to your html parameter. If you do not intend on querying the fixture for #target, consider using `axe.testUtils.fixtureSetup()` instead.'
);
return vNode;
};
/**
* Return the checks evaluate method and apply default options
* @param {string} checkId - ID of the check
* @param {} testOptions - Options for the test
* @returns {evaluateWrapper} evaluateWrapper - Check evaluation wrapper
*/
testUtils.getCheckEvaluate = function getCheckEvaluate(checkId, testOptions) {
const check = checks[checkId];
testOptions = testOptions || {};
/**
* Wraps a check for evaluation using .call()
* @param {HTMLElement} node
* @param {*} options
* @param {VirtualNode} virtualNode
* @param {Context} context
*/
const evaluateWrapper = function (node, options, virtualNode, context) {
const opts = check.getOptions(options);
const result = check.evaluate.call(
this,
node,
opts,
virtualNode,
context
);
// ensure that every result has a corresponding message
if (testOptions.verifyMessage !== false) {
const messages = axe._audit.data.checks[checkId].messages;
const messageKey = this._data && this._data.messageKey;
// see how the check is used to know where to find the message
// e.g. a check used only in the `none` array of a rule will look at
// the messageKey of a passing result in the `fail` messages
let keyResult = result;
const isNoneCheck = noneChecks.indexOf(checkId) !== -1;
if (isNoneCheck) {
keyResult =
result === true ? false : result === false ? true : result;
}
const key =
keyResult === true
? 'pass'
: keyResult === false
? 'fail'
: 'incomplete';
const noneCheckMessage = isNoneCheck
? '. Note that since this check is only used in the "none" array of all rules, the messages use the inverse of the result (e.g. a result of false uses the "pass" messages)'
: '';
assert.exists(
messages[key],
'Missing "' +
key +
'" message for check result of ' +
result +
noneCheckMessage
);
if (messageKey) {
assert.exists(
messages[key][messageKey],
'Missing ' +
key +
' message key "' +
messageKey +
'" for check result of ' +
result +
noneCheckMessage
);
const message = axe.utils.processMessage(
messages[key][messageKey],
this._data
);
assert.isTrue(
message.indexOf('${') === -1,
'Data object missing properties for ' +
key +
' message key "' +
messageKey +
'": "' +
message +
'"'
);
} else {
const message = axe.utils.processMessage(messages[key], this._data);
assert.isTrue(
message.indexOf('${') === -1,
'Data object missing properties for ' +
key +
' message: "' +
message +
'"'
);
}
}
return result;
};
return evaluateWrapper;
};
if (typeof beforeEach !== 'undefined' && typeof afterEach !== 'undefined') {
// prevent setting read-only properties
// @see https://github.com/dequelabs/axe-core/issues/3837
const readonlyRect = new DOMRectReadOnly();
const proto = Object.getPrototypeOf(readonlyRect);
['left', 'right', 'top', 'bottom'].forEach(prop => {
Object.defineProperty(proto, prop, {
set(value) {
throw new TypeError(`setting getter-only property "${prop}"`);
}
});
});
beforeEach(function () {
// reset from axe._load overriding
checks = originalChecks;
axe._audit = originalAudit;
axe._audit.rules = originalRules;
commons = axe.commons = originalCommons;
});
afterEach(function () {
axe.teardown();
fixture.innerHTML = '';
// remove all attributes from fixture (otherwise a leftover
// style attribute would cause avoid-inline-spacing integration
// test to fail with [#fixture] being included in the results)
const attrs = fixture.attributes;
for (let i = 0; i < attrs.length; i++) {
const attrName = attrs[i].name;
if (attrName !== 'id') {
fixture.removeAttribute(attrs[i].name);
}
}
// reset html and body styles
document.body.removeAttribute('style');
document.documentElement.removeAttribute('style');
});
}
testUtils.captureError = function captureError(cb, errorHandler) {
return function () {
try {
cb.apply(null, arguments);
} catch (e) {
errorHandler(e);
}
};
};
testUtils.runPartialRecursive = function runPartialRecursive(
context,
options,
win
) {
options = options || {};
win = win || window;
const axe = win.axe;
const frameContexts = axe.utils.getFrameContexts(context);
let promiseResults = [axe.runPartial(context, options)];
frameContexts.forEach(function (c) {
const frame = testUtils.shadowQuerySelector(
c.frameSelector,
win.document
);
const frameWin = frame.contentWindow;
const frameResults = testUtils.runPartialRecursive(
c.frameContext,
options,
frameWin
);
promiseResults = promiseResults.concat(frameResults);
});
return promiseResults;
};
testUtils.shadowQuerySelector = function shadowQuerySelector(
axeSelector,
doc
) {
let elm;
doc = doc || document;
axeSelector = Array.isArray(axeSelector) ? axeSelector : [axeSelector];
axeSelector.forEach(function (selectorStr) {
elm = doc && doc.querySelector(selectorStr);
doc = elm && elm.shadowRoot;
});
return elm;
};
testUtils.createNestedShadowDom = function createFixtureShadowTree(
fixtureNode,
...htmlCodes
) {
if (htmlCodes.length <= 1) {
throw new Error(
'createNestedShadowDom must contain at least two HTML snippets'
);
}
let htmlCode;
while ((htmlCode = htmlCodes.shift())) {
appendHtml(fixtureNode, htmlCode);
if (htmlCodes.length) {
const query = fixtureNode.querySelectorAll('#shadowHost, .shadowHost');
fixtureNode = query[query.length - 1];
fixtureNode = fixtureNode.attachShadow({ mode: 'open' });
}
}
return fixtureNode.querySelector('#target');
};
/**
* Enables test code like html` <img /> ` to get code highlighting
* @param {array} strings
* @param {...any} values
* @returns {string}
*/
testUtils.html = (strings, ...values) => {
return strings.reduce((total, string, i) => {
return total + string + (values[i] ?? '');
}, '');
};
function appendHtml(fixtureNode, htmlCode) {
const tmp = document.createElement('div');
tmp.innerHTML = htmlCode;
// Append to avoid clobbering other shadow trees with innerHTML
for (let child of tmp.children) {
fixtureNode.appendChild(child.cloneNode(true));
}
}
})();