Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 1 | // Copyright 2019 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | import axe from 'axe-core'; |
| 6 | import userEvent from '@testing-library/user-event'; |
| 7 | import {fireEvent} from '@testing-library/react'; |
| 8 | |
| 9 | // TODO(seanmccullough): Move this into crdx/chopsui-npm if we decide this |
| 10 | // is worth using in other projects. |
| 11 | |
| 12 | /** |
| 13 | * @param {HTMLElement} element The element to audit accessibility for. |
| 14 | */ |
| 15 | export async function auditA11y(element) { |
| 16 | // Performance tip: try restricting the analysis using |
| 17 | // https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#use-resulttypes |
| 18 | const options = {}; |
| 19 | |
| 20 | // Adjust this set to make tests more/less permissible. |
| 21 | const reportImpact = new Set(['critical', 'serious', 'moderate', 'minor']); |
| 22 | const results = await axe.run(element, options); |
| 23 | |
| 24 | if (results.violations.length == 0) { |
| 25 | return; |
| 26 | } |
| 27 | |
| 28 | const msgs = ['Accessibility violations:']; |
| 29 | results.violations.forEach((result) => { |
| 30 | if (reportImpact.has(result.impact)) { |
| 31 | msgs.push(`\n[${result.impact}] ${result.help}`); |
| 32 | for (const node of result.nodes) { |
| 33 | if (node.failureSummary) { |
| 34 | msgs.push(node.failureSummary); |
| 35 | } |
| 36 | msgs.push(node.html); |
| 37 | } |
| 38 | msgs.push('---'); |
| 39 | } |
| 40 | }); |
| 41 | |
| 42 | throw new Error(msgs.join('\n')); |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Types text into an input field and presses Enter. |
| 47 | * @param {HTMLInputElement} input The input field to enter text in. |
| 48 | * @param {string} value The text to enter in the input field. |
| 49 | */ |
| 50 | export function enterInput(input, value) { |
| 51 | userEvent.clear(input); |
| 52 | |
| 53 | userEvent.type(input, value); |
| 54 | |
| 55 | fireEvent.keyDown(input, {key: 'Enter', code: 'Enter'}); |
| 56 | } |
| 57 | |