# cypress-a11y-puppeteer

> A Cypress puppeteer plugin for fetching a11y tree and finding duplicates

Latest version **1.0.15** (published 2024-11-13) · MIT license · 0 weekly downloads

## Install

```sh
npm install cypress-a11y-puppeteer
pnpm add cypress-a11y-puppeteer
yarn add cypress-a11y-puppeteer
bun add cypress-a11y-puppeteer
```

## Health

**Score 25/100 (F)** — status: maintenance-mode.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.15 |
| Published | 2024-11-13 |
| First published | 2024-09-23 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 19 |
| Unpacked size | 47.8 KB |
| Known vulnerabilities | 0 (+25 in 2 direct dependencies) |
| Install scripts | no |
| Author | Kanchan |
| Maintainers | kanchan.bangar |
| Keywords | A, Cypress, plugin, for, fetching, and, validating, a11y, tree |

## Links

- npm: https://www.npmjs.com/package/cypress-a11y-puppeteer
- Repository: https://gitlab.com/conceptboard1/ccs-qa-store-cypress
- Homepage: https://gitlab.com/conceptboard1/ccs-qa-store-cypress#readme
- Issues: https://gitlab.com/conceptboard1/ccs-qa-store-cypress/issues
- npm.io page: https://npm.io/package/cypress-a11y-puppeteer

## Dependencies (19)

- [path](https://npm.io/package/path.md) ^0.12.7
- [axios](https://npm.io/package/axios.md) 0.21.4
- [mocha](https://npm.io/package/mocha.md) 9.2.2
- [dotenv](https://npm.io/package/dotenv.md) ^16.4.5
- [lodash](https://npm.io/package/lodash.md) ^4.17.21
- [cypress](https://npm.io/package/cypress.md) 12.17.4
- [puppeteer](https://npm.io/package/puppeteer.md) ^23.5.3
- [cypress-axe](https://npm.io/package/cypress-axe.md) ^1.5.0
- [browserslist](https://npm.io/package/browserslist.md) 4.19.1
- [caniuse-lite](https://npm.io/package/caniuse-lite.md) 1.0.30001309
- [puppeteer-core](https://npm.io/package/puppeteer-core.md) ^23.1.0
- [junit-report-merger](https://npm.io/package/junit-report-merger.md) 2.2.3
- [mocha-junit-reporter](https://npm.io/package/mocha-junit-reporter.md) 2.0.2
- [cypress-multi-reporters](https://npm.io/package/cypress-multi-reporters.md) 1.5.0
- [cypress-aiotests-reporter](https://npm.io/package/cypress-aiotests-reporter.md) 1.2.0
- [cypress-mochawesome-reporter](https://npm.io/package/cypress-mochawesome-reporter.md) 3.2.0
- [cypress-accessibility-puppeteer](https://npm.io/package/cypress-accessibility-puppeteer.md) ^1.0.0
- [@esbuild-plugins/node-modules-polyfill](https://npm.io/package/@esbuild-plugins/node-modules-polyfill.md) ^0.2.2
- [@badeball/cypress-cucumber-preprocessor](https://npm.io/package/@badeball/cypress-cucumber-preprocessor.md) ^18.0.5

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 1.0.15 (latest) — 2024-11-13
- 1.0.14 — 2024-11-07
- 1.0.13 — 2024-10-17
- 1.0.12 — 2024-10-17
- 1.0.11 — 2024-10-16
- 1.0.10 — 2024-10-16
- 1.0.9 — 2024-10-16
- 1.0.8 — 2024-10-16
- 1.0.7 — 2024-10-14
- 1.0.6 — 2024-10-10
- 1.0.5 — 2024-10-08
- 1.0.4 — 2024-09-30
- 1.0.3 — 2024-09-30
- 1.0.2 — 2024-09-30
- 1.0.1 — 2024-09-23
- … 1 more at https://npm.io/package/cypress-a11y-puppeteer/versions

## README

## Cypress a11y puppeteer plugin

This plugin allows teams to fetch the accessibility (a11y) tree and validate it for duplicates or other issues using Cypress.

### Installation

To install the latest version of the plugin, run the following command:

```bash
npm install cypress-a11y-puppeteer@{version}
```

### Setup

After installing the plugin, you need to add it to your cypress.config.js file.

```feature
Feature: Accessibility tree

@Validate_A11yTree
    Scenario: Fetch a11y tree and find consecutive duplicates using Puppeteer
        Given User is on URL "https://en.wikipedia.org/wiki/World_history"
        Then Fetches the accessibility tree with Puppeteer for "world_history"
        Then Validate a11y tree- find duplicates- find duplicates

    @A11yTree_dialog
    Scenario: Fetch the accessibility tree for a dialog
        Given User is on URL "https://www.airbnb.com/"
        When the user performs steps to open the dialog and fetch a11y tree for "home_page":
            | action | selector                                      | value | selectorToBeVisible |
            | click  | [aria-label="Choose a language and currency"] |       |                     |
# You can pass multiple actions to fetch a11y tree for specific page
# | type            | selector                                      |       |                     |
# | select          | selector                                      |       |                     |
# | hover           | selector                                      |       |                     |
# | waitForSelector | selector                                      |       |                     |
# | waitForTimeout  |                                               | value |                     |
# | focus           | selector                                      |       |                     |
# | scroll          | selector                                      |       |                     |
# | keypress        |                                               | value |                     |

```

#### 1. Update cypress.config.js:

In your `cypress.config.js` file, you need to add the plugin configuration:

```bash
const { fetchA11yTreeForPage, findDuplicates, fetchA11yTreeForDialog, fetchA11yTreeForMenu } = require('cypress-a11y-puppeteer/cypress/plugins/a11yPlugin.js');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on("task", {
        fetchA11yTreeForPage({ url, cookies, localStorageData }) {
          return fetchA11yTreeForPage(url, cookies, localStorageData);
        },
        findDuplicates(a11yTree) {
          return findDuplicates(a11yTree);
        },
        fetchA11yTreeForDialog({ cookies, localStorageData, url, actions }) {
          return fetchA11yTreeForDialog({
            cookies,
            localStorageData,
            url,
            actions,
          });
        },
        fetchA11yTreeForMenu({ cookies, localStorageData, url, actions, menuSelector }) {
          return fetchA11yTreeForMenu({
            cookies,
            localStorageData,
            url,
            actions,
            menuSelector
          });
        },
      });

      // Return the updated config object
      return config;
    },
    // other config options
  },
});

```

### Usage

The plugin adds the following tasks for accessibility tree validation:

#### 1. Fetch Accessibility Tree for page:

This command fetches the accessibility tree of a page using Puppeteer.

```bash
cy.task('fetchA11yTreeForPage', {
  url: 'https://example.com',  // URL to be tested
  cookies: JSON.stringify(cookies), // Optional: pass cookies if required
  localStorageData: JSON.stringify(window.localStorage)  // Optional: pass local storage data if needed
}).then((a11yTree) => {
  cy.wrap(a11yTree).as('a11yTree');
});

```

#### 2. Find duplicates in A11y Tree:

This task identifies duplicate element names in the accessibility tree.

```bash
cy.get('@a11yTree').then((a11yTree) => {
  cy.task('findDuplicates', a11yTree).then((result) => {
    cy.log(result);
  });
});

```

#### 3. Fetch a11y tree when dialogs are open:

This command dynamically performs actions (e.g., clicking buttons) to open a dialog and then fetches the accessibility tree for the dialog.

```bash
cy.task('fetchA11yTreeForDialog', {
  url: 'https://example.com',
  cookies: JSON.stringify(cookies),
  localStorageData: JSON.stringify(window.localStorage),
  actions: [
    { action: 'click', selector: '#dialog-trigger' },
    { action: 'waitForSelector', selector: '.dialog' }
  ]
}).then((a11yTree) => {
  cy.wrap(a11yTree).as('a11yTree');
});

```

#### 3. Fetch a11y tree for menus:

This command dynamically performs actions (e.g., clicking buttons) to navigate to a menu and then fetches the accessibility tree for the menu only.

```bash
cy.task('fetchA11yTreeForMenu', {
  url: 'https://example.com',
  cookies: JSON.stringify(cookies),
  localStorageData: JSON.stringify(window.localStorage),
  menuSelector: menuSelector
  actions: [
    { action: 'click', selector: '#dialog-trigger' },
    { action: 'waitForSelector', selector: '.dialog' }
  ]
}).then((a11yTree) => {
  cy.wrap(a11yTree).as('a11yTree');
});

```

### Writing Test Cases (Cucumber style)

Here's an example of how the plugin can be used in your Cypress tests:

```bash
Then(
  "Fetches the accessibility tree with Puppeteer for {string}",
  (component) => {
    a11y_ActualTree_Path =
      "cypress/fixtures/a11y_Data/a11y_FetchedTree/" + component + ".json";
    cy.url().then((currentUrl) => {
      cy.getCookies().then((cookies) => {
        const serializedCookies = JSON.stringify(cookies);

        cy.window().then((window) => {
          const localStorageData = JSON.stringify(window.localStorage);

          cy.task("fetchA11yTreeForPage", {
            url: currentUrl,
            cookies: serializedCookies,
            localStorageData,
          }).then((a11yTree) => {
            cy.wrap(a11yTree).as("a11yTree");
            cy.writeFile(a11y_ActualTree_Path, a11yTree);
          });
        });
      });
    });
  }
);

Then('Validate a11y tree- find duplicates', () => {
    cy.get('@a11yTree').then((a11yTree) => {
        cy.task('findDuplicates', a11yTree).then((result) => {
            if (result.status === 'fail') {
                // If duplicates are found, throw an error with the detailed message
                throw new Error(`Duplicates found: ${JSON.stringify(result.duplicates)}`);
            } else {
                // If no duplicates are found, log the success message
                cy.log(result.message); // Log the result message
            }
        });
    });
});

Then(
  "the user performs steps to open the dialog and fetch a11y tree for dialog {string}:",
  (component, dataTable) => {
    a11y_ActualTree_Path =
      "cypress/fixtures/a11y_Data/a11y_FetchedTree/" + component + ".json";
    cy.getCookies().then((cookies) => {
      const serializedCookies = JSON.stringify(cookies);

      cy.window().then((window) => {
        const url = window.location.href;
        const localStorageData = JSON.stringify(window.localStorage);

        const actions = dataTable.hashes(); // Actions from the table

        cy.task(
          "fetchA11yTreeForDialog",
          {
            cookies: serializedCookies,
            localStorageData,
            actions,
            url: url, // Pass the correct URL
          },
          { timeout: 120000 }
        ).then((result) => {
          cy.log(JSON.stringify(result.a11yTree));
          // You can directly validate the a11y tree here
          cy.wrap(result.a11yTree).as("a11yTree"); // Store the a11y tree if needed
          cy.writeFile(a11y_ActualTree_Path, result.a11yTree);
        });
      });
    });
  }
);

Then(
  "the user performs steps to navigate to menu and fetch a11y tree for menu {string}:",
  (component, dataTable) => {
    const a11y_ActualTree_Path = "cypress/fixtures/a11y_data/actualA11yTrees/" + component + ".json";
    const a11y_ExpTree_Path = "cypress/fixtures/a11y_data/expectedA11yTrees/" + component + ".json";

    cy.getCookies().then((cookies) => {
      const serializedCookies = JSON.stringify(cookies);

      cy.window().then((window) => {
        const url = window.location.href;
        const localStorageData = JSON.stringify(window.localStorage);

        const actions = dataTable.hashes(); // Parse actions from the data table
        const menuSelector = actions[0].menuSelectorForFetchingTree; // Get menu selector from the table

        // Fetch the accessibility tree for the specified menu
        cy.task(
          "fetchA11yTreeForMenu",
          {
            cookies: serializedCookies,
            localStorageData,
            actions,
            url, // Current page URL
            menuSelector, // Selector for the menu element
          },
          { timeout: 120000 }
        ).then((result) => {
          cy.log(JSON.stringify(result.a11yTree));
          cy.wrap(result.a11yTree).as("a11yTree"); // Store the a11y tree
          cy.writeFile(a11y_ActualTree_Path, result.a11yTree); // Save actual a11y tree

          // // Optional: Compare actual tree with expected tree
          // cy.readFile(a11y_ActualTree_Path).then((actualTree) => {
          //   cy.readFile(a11y_ExpTree_Path).then((expectedTree) => {
          //     expect(actualTree).to.deep.equal(expectedTree);
          //   });
          // });
        });
      });
    });
  }
);

```

### Available Tasks

`fetchA11yTreeForPage`: The first `Then` block fetches the current URL, cookies, and local storage data, and passes them to the fetchA11yTreeForPage task, which retrieves the accessibility tree from the page.

`findDuplicates`: The second `Then` block uses the `findDuplicates` task to validate the accessibility tree and logs the result.

`fetchA11yTreeForDialog`: The third `Then` block uses the `fetchA11yTreeForDialog` task to fetch the accessibility tree for a dialog after performing actions like clicking buttons.

`fetchA11yTreeForMenu`: The third `Then` block uses the `fetchA11yTreeForMenu` task to fetch the accessibility tree for a menu after performing actions like clicking buttons.

## Contributing

We welcome contributions from the community! Please review our [Contribution Guide](CONTRIBUTING.md) and adhere to our [Code of Conduct](CODE_OF_CONDUCT.md) when participating.

If you encounter any issues or have feature requests, please report them in our [Issues section](https://github.com/your-repo/your-project/issues).

## Code of Conduct

This project adheres to a [Code of Conduct](CODE_OF_CONDUCT.md). Please review it before participating.

## Reporting Issues

Please check the [Issues](https://gitlab.com/conceptboard1/ccs-qa-store-cypress/-/issues) page for existing bugs and report new ones if needed.

---
_Source: https://npm.io/package/cypress-a11y-puppeteer · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
