1.0.13 • Published 20 hours ago

cypress-a11y-puppeteer v1.0.13

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
20 hours ago

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:

npm install cypress-a11y-puppeteer@{version}

Setup

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

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:

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

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

      // 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:

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

cy.task('fetchA11yTree', {
  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.

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.

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');
});

Writing Test Cases (Cucumber style)

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

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("fetchA11yTree", {
            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);
        });
      });
    });
  }
);

Available Tasks

fetchA11yTree: The first Then block fetches the current URL, cookies, and local storage data, and passes them to the fetchA11yTree 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.

Contributing

We welcome contributions from the community! Please review our Contribution Guide and adhere to our Code of Conduct when participating.

If you encounter any issues or have feature requests, please report them in our Issues section.

Code of Conduct

This project adheres to a Code of Conduct. Please review it before participating.

Reporting Issues

Please check the Issues page for existing bugs and report new ones if needed.