-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathautomaticMatcher.test.ts
More file actions
305 lines (275 loc) · 12.2 KB
/
automaticMatcher.test.ts
File metadata and controls
305 lines (275 loc) · 12.2 KB
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
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { runAutomaticCheck, skipTest, registerCustomSa11yRules } from '../src';
import {
beforeEachSetup,
domWithA11yIssues,
domWithNoA11yIssues,
domWithNoA11yIssuesChildCount,
domWithDescendancyA11yIssues,
customRulesFilePath,
domWithA11yCustomIssues,
domWithA11yIncompleteIssues,
} from '@sa11y/test-utils';
import { expect } from '@jest/globals';
import {
setOriginalDocumentBodyHtml,
getOriginalDocumentBodyHtml,
observerOptions,
defaultAutoCheckOpts,
defaultRenderedDOMSaveOpts,
} from '../src/automatic';
import * as common from '@sa11y/common';
import * as assert from '@sa11y/assert';
describe('automatic checks call', () => {
const testPath = expect.getState().testPath || 'defaultPath';
const testName = expect.getState().currentTestName || 'defaultTestName';
const nonExistentFilePaths = ['foo', `foo${testPath}`, `${testPath}foo`];
// Note: cleanup required at end of each test to prevent dom being checked again
// after the test as part of the afterEach automatic check hook
beforeEach(beforeEachSetup);
it('should not raise a11y issues for DOM without a11y issues', () => {
document.body.innerHTML = domWithNoA11yIssues;
return expect(runAutomaticCheck()).resolves.not.toThrow();
});
it('should raise a11y issues for DOM with a11y issues', async () => {
document.body.innerHTML = domWithA11yIssues;
await expect(runAutomaticCheck({ cleanupAfterEach: true })).rejects.toThrow('1 Accessibility');
});
test.each([0, 1, 2, 3])(
'should raise consolidated a11y issues for DOM with multiple a11y issues',
async (numNodesWithIssues: number) => {
document.body.innerHTML = domWithA11yIssues;
// Note: Create multiple children in body with a11y issues
for (let i = 0; i < numNodesWithIssues; i++) {
document.body.innerHTML += `<a id="link-${i}" href="#"></a>`;
}
await expect(runAutomaticCheck({ cleanupAfterEach: true })).rejects.toThrow();
}
);
it('should cleanup DOM by default', async () => {
document.body.innerHTML = domWithNoA11yIssues;
expect(document.body.childElementCount).toBe(domWithNoA11yIssuesChildCount);
await runAutomaticCheck();
expect(document.body.childElementCount).toBe(0);
});
it('should not cleanup DOM when opted out', async () => {
document.body.innerHTML = domWithNoA11yIssues;
expect(document.body.childElementCount).toBe(domWithNoA11yIssuesChildCount);
await runAutomaticCheck({ cleanupAfterEach: false });
expect(document.body.childElementCount).toBe(domWithNoA11yIssuesChildCount);
});
it('should not raise error for duplicated issues', async () => {
// TODO (Refactor): extract out duplicated code to set dom, expect assertions and invoke automatic check
document.body.innerHTML = domWithA11yIssues;
const opts = { cleanupAfterEach: false, consolidateResults: true };
await expect(runAutomaticCheck(opts)).rejects.toThrow();
// Should not throw error for the same DOM with consolidation
await expect(runAutomaticCheck(opts)).resolves.toBeUndefined();
// Should throw error again without consolidation
await expect(runAutomaticCheck({ cleanupAfterEach: true, consolidateResults: false })).rejects.toThrow();
});
it('should skip descendancy checks', async () => {
document.body.innerHTML = domWithDescendancyA11yIssues;
const opts = { cleanupAfterEach: false };
await expect(runAutomaticCheck(opts)).resolves.toBeUndefined();
});
test.each([
['foo', undefined, false],
['foo', [], false],
['foo', ['foo'], true],
['foo', ['Foo'], true],
['foo', ['foo', 'bar'], true],
['foo', ['bar'], false],
['foo', ['foobar'], false],
['foo', ['barfoo'], false],
])(
'should filter test file as expected with args # %#',
(testPath: string, filesFilter: string[] | undefined, expectedResult: boolean) => {
expect(skipTest(testPath, filesFilter)).toBe(expectedResult);
}
);
it('should skip auto checks when file is excluded using filter', async () => {
document.body.innerHTML = domWithA11yIssues;
await expect(
runAutomaticCheck(
{ filesFilter: [...nonExistentFilePaths, testPath] },
{ renderedDOMDumpDirPath: '' },
testPath,
testName
)
).resolves.toBeUndefined();
});
it('should run auto checks when file is not excluded using filter', async () => {
document.body.innerHTML = domWithA11yIssues;
await expect(runAutomaticCheck({ filesFilter: nonExistentFilePaths })).rejects.toThrow();
});
it('should incomplete rules', async () => {
registerCustomSa11yRules();
document.body.innerHTML = domWithA11yIncompleteIssues;
process.env.SA11Y_CUSTOM_RULES = customRulesFilePath;
await expect(
runAutomaticCheck({ cleanupAfterEach: true, enableIncompleteResults: true, consolidateResults: true })
).rejects.toThrow('2 Accessibility');
delete process.env.SA11Y_CUSTOM_RULES;
});
it('should take only custom rules if specified/testing for new rule', async () => {
registerCustomSa11yRules();
document.body.innerHTML = domWithA11yCustomIssues;
process.env.SA11Y_CUSTOM_RULES = customRulesFilePath;
await expect(runAutomaticCheck({ cleanupAfterEach: true })).rejects.toThrow('1 Accessibility');
delete process.env.SA11Y_CUSTOM_RULES;
});
it('should pass filter selector keywords', async () => {
registerCustomSa11yRules();
document.body.innerHTML = domWithA11yIssues;
process.env.SELECTOR_FILTER_KEYWORDS = 'lightning-';
await expect(runAutomaticCheck({ filesFilter: nonExistentFilePaths })).rejects.toThrow();
delete process.env.SELECTOR_FILTER_KEYWORDS;
});
it('should pass when run in DOM Mutation Observer mode', async () => {
document.body.innerHTML = domWithA11yIssues;
await expect(
runAutomaticCheck(
{ filesFilter: [...nonExistentFilePaths, testPath], runDOMMutationObserver: true },
{ renderedDOMDumpDirPath: '' },
testPath,
testName
)
).resolves.toBeUndefined();
});
it('should take only custom rules if specified/testing for new rule in DOM Mutation Observer mode', async () => {
registerCustomSa11yRules();
document.body.innerHTML = domWithA11yCustomIssues;
process.env.SA11Y_CUSTOM_RULES = customRulesFilePath;
await expect(runAutomaticCheck({ cleanupAfterEach: true, runDOMMutationObserver: true })).rejects.toThrow(
'1 Accessibility'
);
delete process.env.SA11Y_CUSTOM_RULES;
});
});
describe('automatic.ts exports', () => {
afterEach(() => {
setOriginalDocumentBodyHtml(null);
});
it('setOriginalDocumentBodyHtml and getOriginalDocumentBodyHtml should set and get the value', () => {
setOriginalDocumentBodyHtml('<div>test</div>');
expect(getOriginalDocumentBodyHtml()).toBe('<div>test</div>');
setOriginalDocumentBodyHtml(null);
expect(getOriginalDocumentBodyHtml()).toBeNull();
});
it('observerOptions should have the correct structure', () => {
expect(observerOptions).toEqual({
subtree: true,
childList: true,
attributes: true,
characterData: true,
});
});
it('defaultAutoCheckOpts should have the correct defaults', () => {
expect(defaultAutoCheckOpts).toEqual({
runAfterEach: true,
cleanupAfterEach: true,
consolidateResults: true,
filesFilter: [],
runDOMMutationObserver: false,
enableIncompleteResults: false,
});
});
it('defaultRenderedDOMSaveOpts should have the correct defaults', () => {
expect(defaultRenderedDOMSaveOpts).toEqual({
renderedDOMDumpDirPath: '',
});
});
});
describe('runAutomaticCheck runDOMMutationObserver checks', () => {
const mockViolations = [
{
id: 'aria-allowed-attr',
impact: 'serious',
tags: ['cat.aria', 'wcag2a', 'wcag412'],
description: "Ensures ARIA attributes are allowed for an element's role",
help: 'Elements must only use allowed ARIA attributes',
helpUrl: 'https://dequeuniversity.com/rules/axe/4.7/aria-allowed-attr?application=axeAPI',
nodes: [
{
any: [],
all: [],
none: [
{
id: 'aria-prohibited-attr',
data: {
role: null,
nodeName: 'lightning-button-icon',
messageKey: 'noRoleSingular',
prohibited: ['aria-label'],
},
relatedNodes: [],
message:
'aria-label attribute cannot be used on a lightning-button-icon with no valid role attribute.',
},
],
html: '<lightning-button-icon lwc-2pdnejk934a="" class="slds-button slds-button_icon slds-button_icon-small slds-float_right slds-popover__close" aria-label="AgentWhisper.CloseDialog" title="AgentWhisper.CloseDialog"></lightning-button-icon>',
target: ['lightning-button-icon'],
},
],
},
];
afterEach(() => {
setOriginalDocumentBodyHtml(null);
delete process.env.SELECTOR_FILTER_KEYWORDS;
jest.restoreAllMocks();
});
it('should early return if isFakeTimerUsed returns true', async () => {
const spy = jest.spyOn(common, 'useCustomRules');
await runAutomaticCheck({}, {}, '', '', () => true);
expect(spy).not.toHaveBeenCalled();
});
it('should restore originalDocumentBodyHtml if set', async () => {
document.body.innerHTML = '<div>changed</div>';
setOriginalDocumentBodyHtml('<div>original</div>');
await runAutomaticCheck();
expect(document.body.innerHTML).toBe('');
});
it('should handle runDOMMutationObserver with file save and error', async () => {
const writeHtmlSpy = jest.spyOn(common, 'writeHtmlFileInPath').mockImplementation(() => {
throw new Error('fail');
});
jest.spyOn(assert, 'getA11yResultsJSDOM').mockImplementation(() => {
return new Promise((resolve) => {
resolve(mockViolations as unknown as common.AxeResults);
});
});
const opts = {
runDOMMutationObserver: true,
};
const renderedDOMSaveOpts = {
renderedDOMDumpDirPath: 'dir',
generateRenderedDOMFileSaveLocation: () => ({ fileName: 'file.html', fileUrl: 'url' }),
};
document.body.innerHTML = '<div>test</div>';
try {
await runAutomaticCheck(opts, renderedDOMSaveOpts, 'testPath', 'testName');
} catch (e) {
// empty here to avoid jest error
}
expect(writeHtmlSpy).toHaveBeenCalled();
});
it('should handle runDOMMutationObserver with missing testPath/testName', async () => {
const writeHtmlSpy = jest.spyOn(common, 'writeHtmlFileInPath');
const opts = {
runDOMMutationObserver: true,
};
const renderedDOMSaveOpts = {
renderedDOMDumpDirPath: 'dir',
generateRenderedDOMFileSaveLocation: () => ({ fileName: 'file.html', fileUrl: 'url' }),
};
document.body.innerHTML = '<div>test</div>';
await runAutomaticCheck(opts, renderedDOMSaveOpts, '', '');
expect(writeHtmlSpy).not.toHaveBeenCalled();
});
});