3

I am facing following error while running lwc test in newly created Salesforce DX project. I have installed JEST using sfdx force:lightning:lwc:test:setup command.

This error I am facing only for assertion await expect(element).toBeAccessible(); For other assertion expect(div.textContent).toBe('Hello, World!'); No error.

TypeError: expect(...).toBeAccessible is not a function
    at Object.toBeAccessible (C:\Users\JEST\JESTProject\force-app\main\default\lwc\hello\__tests__\hello.test.js:26:31)
    at Promise.then.completed (C:\Users\\JEST\JESTProject\node_modules\jest-circus\build\utils.js:333:28)
    at new Promise (<anonymous>)
    at callAsyncCircusFn ..........................................

lwc component and test is copied from lwc recipe repository - https://github.com/trailheadapps/lwc-recipes/tree/main/force-app/main/default/lwc/hello

   it('is accessible', async () => {
        const element = createElement('c-hello', {
            is: Hello
        });
        document.body.appendChild(element);

        await expect(element).toBeAccessible();
    });

If I am running this test in project cloned from lwc recipe repository then I am not facing this issue.

1 Answer 1

6

Jest by default does not support testing Accessibility.

You will need to make sure you use the Salesforce Accessibility Automation Libraries

We have a blog post detailing how to setup and get started with it.

Key Steps are as follows

  1. Make sure to Install @sa11y/jest as dev dependency.

    npm install -D @sa11y/jest

  2. Create a setup file that registers the toBeAccessible() sa11y matcher so that it can be used with expect()

You will need a file named jest-sa11y-setup.js with below code

import { registerSa11yMatcher } from '@sa11y/jest';

registerSa11yMatcher();
  1. Include the newly created setup file into your generic jest config file. So your jest.config.js file should look like below

     const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
    
    const setupFilesAfterEnv = jestConfig.setupFilesAfterEnv || [];
    setupFilesAfterEnv.push('<rootDir>/jest-sa11y-setup.js');
    
    module.exports = {
        ...jestConfig,
        setupFilesAfterEnv
    };
    

Once you have all the above your Jest code should work fine.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .