Skip to content
Building UI Design Systems

Lesson 6 of 6 · 20 min

x
6/6

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

Testing UI Components with Testing Library & Playwright

Testing design system components ensures that accessibility attributes, variants, and interactive states remain stable across software releases. Component testing prioritizes user-centric queries — searching for elements by accessible role (getByRole('button', { name: /submit/i })) rather than CSS selectors.

Unit and component tests (using React Testing Library) verify prop rendering and event firing, while visual regression tests (using Playwright screenshots) compare visual pixel outputs across browsers to catch unintentional CSS breakages.

Before
Fragile Implementation Detail Test Query
1// ❌ Fragile: Breaks if CSS class or HTML tag changes2const btn = container.querySelector('.btn-primary-lg');3fireEvent.click(btn);
After
Accessible Role-Based Component Test
1import { render, screen } from '@testing-library/react';2import userEvent from '@testing-library/user-event';3import { Button } from './button';4 5test('triggers onClick when activated by user', async () => {6  const handleClick = jest.fn();7  render(<Button onClick={handleClick}>Submit</Button>);8 9  const button = screen.getByRole('button', { name: /submit/i });10  await userEvent.click(button);11 12  expect(handleClick).toHaveBeenCalledTimes(1);13});

Exercise

Write a React Testing Library test for an Accordion component verifying that clicking the header expands the panel and updates aria-expanded.

Check your understanding

  • Why are role-based queries (getByRole) preferred over CSS selectors in testing?Show answer

    Answer

    They test the UI from the user and screen reader's perspective, making tests resilient to refactoring.
  • What is visual regression testing in UI development?Show answer

    Answer

    Comparing browser screenshot images of components against baseline reference snapshots to detect visual pixel changes.
Previous

Progress is saved in this browser.

Finish Course