Testing Exercise
Let’s write some automated tests for our Portal Switcher component with Jest and Testing Library. You can also write tests for other tools, including Cypress.
Here is the (inaccessible) component once again. You can find this exercise and a more accessible component in the completed-components/exercise-5-tests
directory and on GitHub (opens in a new tab).
Test Suggestions
Here are some suggestions for automated accessibility tests. Try to implement them / make them pass by fixing the Portal Switcher code.
Unit testing with Jest and Testing Library:
it('toggles the portal switcher with the keyboard', async () => {
// find elements
const toggleButton = screen.getByRole('button', { name: /Toggle portal menu/ });
// call userEvent for keyboard events
// assert that the component responds to events with
// focus, ARIA states, text in the document, etc.
});
Testing with Cypress-Axe (opens in a new tab) involves writing test cases in the cypress/e2e
directory:
it('should have no accessibility violations', () => {
cy.checkA11y({
exclude: ['div#portal-root'],
});
// check output in the browser console
});