forked from NickColley/jest-axe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
194 lines (171 loc) · 6.17 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
"use strict";
const axeCore = require("axe-core");
const merge = require("lodash.merge");
const chalk = require("chalk");
const { printReceived, matcherHint } = require("jest-matcher-utils");
/**
* Converts a HTML string or HTML element to a mounted HTML element.
* @param {Element | string} a HTML element or a HTML string
* @returns {[Element, function]} a HTML element and a function to restore the document
*/
function mount(html) {
if (isHTMLElement(html)) {
if (document.body.contains(html)) {
return [html, () => undefined];
}
html = html.outerHTML;
}
if (isHTMLString(html)) {
const originalHTML = document.body.innerHTML;
const restore = () => {
document.body.innerHTML = originalHTML;
};
document.body.innerHTML = html;
return [document.body, restore];
}
if (typeof html === "string") {
throw new Error(`html parameter ("${html}") has no elements`);
}
throw new Error(`html parameter should be an HTML string or an HTML element`);
}
/**
* Small wrapper for axe-core#run that enables promises (required for Jest),
* default options and injects html to be tested
* @param {object} [options] default options to use in all instances
* @param {object} [options.globalOptions] Global axe-core configuration (See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#api-name-axeconfigure)
* @param {object} [options.*] Any other property will be passed as the runner configuration (See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter)
* @returns {function} returns instance of axe
*/
function configureAxe(options = {}) {
const { globalOptions = {}, ...runnerOptions } = options;
// Set the global configuration for axe-core
// https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#api-name-axeconfigure
const { checks = [], ...otherGlobalOptions } = globalOptions;
axeCore.configure({
checks: [
{
// color contrast checking doesnt work in a jsdom environment.
id: "color-contrast",
enabled: false,
},
...checks,
],
...otherGlobalOptions,
});
/**
* Small wrapper for axe-core#run that enables promises (required for Jest),
* default options and injects html to be tested
* @param {string} html requires a html string to be injected into the body
* @param {object} [additionalOptions] aXe options to merge with default options
* @returns {promise} returns promise that will resolve with axe-core#run results object
*/
return function axe(html, additionalOptions = {}) {
const [element, restore] = mount(html);
const options = merge({}, runnerOptions, additionalOptions);
return new Promise((resolve, reject) => {
axeCore.run(element, options, (err, results) => {
restore();
if (err) reject(err);
resolve(results);
});
});
};
}
/**
* Checks if the HTML parameter provided is a HTML element.
* @param {Element} a HTML element or a HTML string
* @returns {boolean} true or false
*/
function isHTMLElement(html) {
return !!html && typeof html === "object" && typeof html.tagName === "string";
}
/**
* Checks that the HTML parameter provided is a string that contains HTML.
* @param {string} a HTML element or a HTML string
* @returns {boolean} true or false
*/
function isHTMLString(html) {
return typeof html === "string" && /(<([^>]+)>)/i.test(html);
}
/**
* Filters all violations by user impact
* @param {object} violations result of the accessibilty check by axe
* @param {array} impactLevels defines which impact level should be considered (e.g ['critical'])
* The level of impact can be "minor", "moderate", "serious", or "critical".
* @returns {object} violations filtered by impact level
*/
function filterViolations(violations, impactLevels) {
if (impactLevels && impactLevels.length > 0) {
return violations.filter((v) => impactLevels.includes(v.impact));
}
return violations;
}
/**
* Custom Jest expect matcher, that can check aXe results for violations.
* @param {object} object requires an instance of aXe's results object
* (https://github.com/dequelabs/axe-core/blob/develop-2x/doc/API.md#results-object)
* @returns {object} returns Jest matcher object
*/
const toHaveNoViolations = {
toHaveNoViolations(results) {
if (typeof results.violations === "undefined") {
throw new Error("No violations found in aXe results object");
}
const violations = filterViolations(
results.violations,
results.toolOptions ? results.toolOptions.impactLevels : []
);
const reporter = (violations) => {
if (violations.length === 0) {
return [];
}
const lineBreak = "\n\n";
const horizontalLine = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
return violations
.map((violation) => {
const errorBody = violation.nodes
.map((node) => {
const selector = node.target.join(", ");
const expectedText =
`Expected the HTML found at $('${selector}') to have no violations:` +
lineBreak;
return (
expectedText +
chalk.grey(node.html) +
lineBreak +
`Received:` +
lineBreak +
printReceived(`${violation.help} (${violation.id})`) +
lineBreak +
chalk.yellow(node.failureSummary) +
lineBreak +
(violation.helpUrl
? `You can find more information on this issue here: \n${chalk.blue(
violation.helpUrl
)}`
: "")
);
})
.join(lineBreak);
return errorBody;
})
.join(lineBreak + horizontalLine + lineBreak);
};
const formatedViolations = reporter(violations);
const pass = formatedViolations.length === 0;
const message = () => {
if (pass) {
return;
}
return (
matcherHint(".toHaveNoViolations") + "\n\n" + `${formatedViolations}`
);
};
return { actual: violations, message, pass };
},
};
module.exports = {
configureAxe,
axe: configureAxe(),
toHaveNoViolations,
};