
Security News
npm Adopts OIDC for Trusted Publishing in CI/CD Workflows
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
@sa11y/jest
Advanced tools
@sa11y/jest
Accessibility matcher for Jest
The toBeAccessible()
API from this library can be used in Jest unit tests to test HTML elements or DOM for accessibility.
yarn add -D @sa11y/jest
npm install -D @sa11y/jest
The accessibility APIs need to be registered with Jest before they can be used in tests.
You can set up the sa11y API once at the project level to make it available to all the Jest tests in the project. For an example look at the Integration test setup in @sa11y.
jest-setup.js
) and add the following code that registers the sa11y API// Import using either CommonJS `require` or ES6 `import`
const { setup } = require('@sa11y/jest'); // CommonJS
import { setup } from '@sa11y/jest'; // ES6
// Register the sa11y matcher
setup();
// Register with custom options for automatic checks and DOM saving
setup({
autoCheckOpts: { runAfterEach: true, cleanupAfterEach: true },
renderedDOMSaveOpts: {
/* your RenderedDOMSaveOpts here */
},
});
jest.config.js
at the root of your project, add:module.exports = {
setupFilesAfterEnv: ['<rootDir>/sa11y-jest-setup.js'],
};
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
const setupFilesAfterEnv = jestConfig.setupFilesAfterEnv || [];
setupFilesAfterEnv.push('<rootDir>/jest-sa11y-setup.js');
module.exports = {
...jestConfig,
setupFilesAfterEnv,
};
toBeAccessible
API available for any test in the project.Invoke setup
before using the toBeAccessible
API in the tests
import { setup } from '@sa11y/jest';
beforeAll(() => {
setup();
});
toBeAccessible
API available for the tests only in that specific test module where setup()
is invoked.toBeAccessible
can either be invoked on the entire document
(JSDOM) or on a specific HTML element to check for accessibilityimport { extended, full } from '@sa11y/preset-rules';
import { setup } from '@sa11y/jest';
beforeAll(() => {
setup();
});
it('should be accessible', async () => {
// Setup DOM to be tested for accessibility
//...
// assert that DOM is accessible (using base preset-rule)
await expect(document).toBeAccessible();
// Can be used to test accessibility of a specific HTML element
const elem = document.getElementById('foo');
await expect(elem).toBeAccessible();
// To test using an extended ruleset with best practices and experimental rules
await expect(document).toBeAccessible(extended);
// To test using all rules provided by axe
await expect(document).toBeAccessible(full);
});
toBeAccessible
must be invoked with async/wait
or Promise
or the equivalent supported asynchronous method in your environment
Promise
should not be mixed together with async/wait
. Doing so could result in Jest timeout and other errors.Axe is already running. Use await axe.run() to wait for the previous run to finish before starting a new run.
try running tests serially by using Jest's run in band option.jest.useFakeTimers()
) accessibility API can timeout. Before invoking the accessibility API switch to the real timer (e.g. jest.useRealTimers()
).<template>
elements are not rendered in DOM and hence cannot be checked directly without rendering. They have to be rendered before they can be checked.Following rules are disabled for the Sa11y Jest API
audio
, video
elements cannot be checked as they are stubbed out in JSDOM@sa11y/wdio
The Sa11y Jest API can be setup to be automatically invoked at the end of each test as an alternative to adding the toBeAccessible
API at the end of each test.
setup({ autoCheckOpts: { runAfterEach: true } });
// To optionally cleanup the body after running a11y checks
setup({ autoCheckOpts: { runAfterEach: true, cleanupAfterEach: true } });
// To customize how/where the rendered DOM is saved during automatic checks
setup({
autoCheckOpts: { runAfterEach: true },
renderedDOMSaveOpts: {
/* your RenderedDOMSaveOpts here */
},
});
Automatic checks can also be enabled using environment variables
SA11Y_AUTO=1 SA11Y_CLEANUP=1 jest
jest
with environment variables as above will enable automatic checks with no changes required to setup()
setup()
to opt-in to automatic checksSA11Y_DEBUG=1
will output verbose loggingSA11Y_AUTO_FILTER
can be used to specify a comma seperated list of test file paths to filter out from automatic checks. When specified automatic checks are skipped for given files.The sa11y custom test results processor can be enabled using e.g., - jest --json --outputFile results.json --testResultsProcessor node_modules/@sa11y/jest/dist/resultsProcessor.js
With default results processor - a11y error is embedded within the test failure:
{
"assertionResults": [
{
"ancestorTitles": ["integration test @sa11y/jest"],
"failureMessages": [
"A11yError: 1 Accessibility issues found\n * (link-name) Links must have discernible text: a\n\t- Help URL: https://dequeuniversity.com/rules/axe/4.1/link-name\n at Function.checkAndThrow (packages/format/src/format.ts:67:19)\n at automaticCheck (packages/jest/src/automatic.ts:54:19)\n at Object.<anonymous> (packages/jest/src/automatic.ts:69:13)"
],
"fullName": "integration test @sa11y/jest should throw error for inaccessible dom",
"location": null,
"status": "failed",
"title": "should throw error for inaccessible dom"
}
]
}
With sa11y results processor:
{
"assertionResults": [
{
"ancestorTitles": ["integration test @sa11y/jest"],
"failureMessages": [
"A11yError: 1 Accessibility issues found\n * (link-name) Links must have discernible text: a\n\t- Help URL: https://dequeuniversity.com/rules/axe/4.1/link-name\n at Function.checkAndThrow (packages/format/src/format.ts:67:19)\n at automaticCheck (packages/jest/src/automatic.ts:54:19)\n at Object.<anonymous> (packages/jest/src/automatic.ts:69:13)"
],
"fullName": "integration test @sa11y/jest should throw error for inaccessible dom",
"location": null,
"status": "disabled",
"title": "should throw error for inaccessible dom"
}
]
}
{
"assertionResults": [
{
"ancestorTitles": [
"integration test @sa11y/jest",
"integration test @sa11y/jest should throw error for inaccessible dom"
],
"failureMessages": [
"Accessibility issues found: Links must have discernible text\nCSS Selectors: a\nHTML element: <a href=\"#\"></a>\nHelp: https://dequeuniversity.com/rules/axe/4.1/link-name\nTests: \"integration test @sa11y/jest should throw error for inaccessible dom\"\nSummary: Fix all of the following:\n Element is in tab order and does not have accessible text\n\nFix any of the following:\n Element does not have text that is visible to screen readers\n aria-label attribute does not exist or is empty\n aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty\n Element has no title attribute"
],
"fullName": "[Sa11y WCAG2.0-LevelA-SC4.1.2] Links must have discernible text: a",
"location": null,
"status": "failed",
"title": "should throw error for inaccessible dom"
}
]
}
Automatic checks currently has the following limitations.
cleanupAfterEach: true
or SA11Y_CLEANUP=1
)toBeAccessible
Jest API (disabled-checks)@sa11y/matcher
: Provides the core accessibility checking APIs used by this package. Use it directly for custom test runners or advanced integrations.autoCheckOpts
: Options for automatic accessibility checks (see below)renderedDOMSaveOpts
: Options for saving the rendered DOM during automatic checks. Allows customizing how and where the DOM is saved for debugging or reporting purposes. See @sa11y/matcher
RenderedDOMSaveOpts for details.autoCheckOpts:
runAfterEach
: Run after each test (for integration with test runners)cleanupAfterEach
: Clean up the DOM after checkingconsolidateResults
: Deduplicate resultsfilesFilter
: Array of file path substrings to skip automatic checks forrunDOMMutationObserver
: Enable DOM mutation observer modeenableIncompleteResults
: Include incomplete resultsSA11Y_AUTO
: Enable automatic checks (1
to enable)SA11Y_CLEANUP
: Clean up the DOM after checking (1
to enable)SA11Y_DEBUG
: Output verbose logging (1
to enable)SA11Y_AUTO_FILTER
: Comma-separated list of test file paths to filter out from automatic checksSA11Y_RULESET
: Override the default ruleset (base
, extended
, or full
)SA11Y_RULESET_PRIORITY
: Select rules of specified priority in a rulesetFAQs
Accessibility testing matcher for Jest
We found that @sa11y/jest demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
Research
/Security News
A RubyGems malware campaign used 60 malicious packages posing as automation tools to steal credentials from social media and marketing tool users.
Security News
The CNA Scorecard ranks CVE issuers by data completeness, revealing major gaps in patch info and software identifiers across thousands of vulnerabilities.