front-end-testing

1
1
Source

DOM Testing Library patterns for behavior-driven UI testing. Framework-agnostic patterns for testing user interfaces. Use when testing any front-end application.

Install

mkdir -p .claude/skills/front-end-testing && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4287" && unzip -o skill.zip -d .claude/skills/front-end-testing && rm skill.zip

Installs to .claude/skills/front-end-testing

About this skill

Front-End Testing

For React-specific patterns (components, hooks, context), load the react-testing skill. For TDD workflow, load the tdd skill. For general testing patterns (factories, public API testing), load the testing skill.

Vitest Browser Mode (Preferred)

Always prefer Vitest Browser Mode over jsdom/happy-dom. Tests run in a real browser (via Playwright), giving production-accurate behavior for CSS, events, focus management, and accessibility.

Why Browser Mode Over jsdom

Aspectjsdom/happy-domBrowser Mode
EnvironmentSimulated DOM in Node.jsReal browser (Chromium/Firefox/WebKit)
CSSNot renderedReal CSS rendering, layout, computed styles
EventsSynthetic JS eventsCDP-based real browser events
APIsSubset of Web APIsFull browser API surface
Focus/a11yApproximateReal focus management, accessibility tree
DebuggingConsole onlyFull browser DevTools

Setup

npm install -D vitest @vitest/browser-playwright
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import { playwright } from '@vitest/browser-playwright'

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: playwright(),
      headless: true,
      instances: [{ browser: 'chromium' }],
    },
  },
})

Quick setup wizard: npx vitest init browser

Built-in Locators

Vitest Browser Mode has built-in locators that mirror Testing Library queries. No separate @testing-library/dom import needed.

import { page } from 'vitest/browser'

// These work exactly like Testing Library queries
page.getByRole('button', { name: /submit/i })
page.getByText(/welcome/i)
page.getByLabelText(/email/i)
page.getByPlaceholder(/search/i)
page.getByAltText(/logo/i)
page.getByTestId('my-element')  // Last resort only

Built-in Assertions with Retry

Use expect.element() for DOM assertions — it automatically retries until the assertion passes or times out, reducing flakiness:

// ✅ CORRECT - Auto-retrying assertion
await expect.element(page.getByText(/success/i)).toBeVisible()
await expect.element(page.getByRole('button')).toBeDisabled()

// Available matchers (no @testing-library/jest-dom needed):
await expect.element(el).toBeVisible()
await expect.element(el).toBeDisabled()
await expect.element(el).toHaveTextContent(/text/i)
await expect.element(el).toHaveValue('input value')
await expect.element(el).toHaveAttribute('aria-label', 'Close')
await expect.element(el).toBeChecked()

Built-in User Events (CDP-based)

import { userEvent } from 'vitest/browser'

// Real browser events via Chrome DevTools Protocol
await userEvent.click(page.getByRole('button', { name: /submit/i }))
await userEvent.fill(page.getByLabelText(/email/i), '[email protected]')
await userEvent.keyboard('{Enter}')
await userEvent.selectOptions(page.getByLabelText(/country/i), 'USA')
await userEvent.clear(page.getByLabelText(/search/i))

Or use locator methods directly:

await page.getByRole('button', { name: /submit/i }).click()
await page.getByLabelText(/email/i).fill('[email protected]')

Multi-Project Setup (Node + Browser)

When you need both unit tests (Node) and UI tests (browser):

export default defineConfig({
  test: {
    projects: [
      {
        test: {
          include: ['tests/unit/**/*.test.ts'],
          name: 'unit',
          environment: 'node',
        },
      },
      {
        test: {
          include: ['tests/browser/**/*.test.ts'],
          name: 'browser',
          browser: {
            enabled: true,
            provider: playwright(),
            instances: [{ browser: 'chromium' }],
          },
        },
      },
    ],
  },
})

Browser Mode Gotchas

  • vi.spyOn on imports: ES module namespaces are sealed in real browsers. Use vi.mock('./module', { spy: true }) instead.
  • alert()/confirm(): Thread-blocking dialogs halt browser execution. Mock them with vi.spyOn(window, 'alert').mockImplementation(() => {}).
  • act() not needed: CDP events + expect.element() retry handle timing automatically.

Playwright / Browser Mode Test Idempotency

All Playwright-style tests MUST be idempotent. Every test must produce the same result regardless of execution order, how many times it runs, or what other tests ran before it.

Rules:

  • Each test creates its own state from scratch — never depend on another test's side effects
  • Clean up any persistent state (database rows, localStorage, cookies) created during the test
  • Use unique identifiers (e.g., timestamp-based) to avoid collisions when tests run in parallel
  • Never assume the DOM is in a particular state at the start of a test — render fresh
  • If tests share a server or database, use isolation strategies (transactions, test-specific data)
// ❌ WRONG - Tests depend on shared state
it('creates a user', async () => {
  await page.getByRole('button', { name: /create/i }).click()
  // Creates user "Alice" in the database
})

it('lists users', async () => {
  // Assumes "Alice" exists from previous test!
  await expect.element(page.getByText('Alice')).toBeVisible()
})

// ✅ CORRECT - Each test is self-contained
it('creates and displays a user', async () => {
  const uniqueName = `User-${Date.now()}`
  await page.getByLabelText(/name/i).fill(uniqueName)
  await page.getByRole('button', { name: /create/i }).click()
  await expect.element(page.getByText(uniqueName)).toBeVisible()
})

Why this matters: Browser Mode can run tests in parallel across multiple browser instances. Non-idempotent tests will produce flaky failures that are nearly impossible to debug.


Legacy: DOM Testing Library Patterns

The patterns below apply when using @testing-library/dom directly (e.g., with jsdom). Prefer Vitest Browser Mode for new projects — the query patterns are identical but built-in.


Core Philosophy

Test behavior users see, not implementation details.

Testing Library exists to solve a fundamental problem: tests that break when you refactor (false negatives) and tests that pass when bugs exist (false positives).

Two Types of Users

Your UI components have two users:

  1. End-users: Interact through the DOM (clicks, typing, reading text)
  2. Developers: You, refactoring implementation

Kent C. Dodds principle: "The more your tests resemble the way your software is used, the more confidence they can give you."

Why This Matters

False negatives (tests break on refactor):

// ❌ WRONG - Testing implementation (will break on refactor)
it('should update internal state', () => {
  const component = new CounterComponent();
  component.setState({ count: 5 }); // Coupled to state implementation
  expect(component.state.count).toBe(5);
});

False positives (bugs pass tests):

// ❌ WRONG - Testing wrong thing
it('should render button', () => {
  render('<button data-testid="submit-btn">Submit</button>');
  expect(screen.getByTestId('submit-btn')).toBeInTheDocument();
  // Button exists but onClick is broken - test passes!
});

Correct approach (behavior-driven):

// ✅ CORRECT - Testing user-visible behavior
it('should submit form when user clicks submit', async () => {
  const handleSubmit = vi.fn();
  const user = userEvent.setup();

  render(`
    <form id="login-form">
      <label>Email: <input name="email" /></label>
      <label>Password: <input name="password" type="password" /></label>
      <button type="submit">Submit</button>
    </form>
  `);

  document.getElementById('login-form').addEventListener('submit', (e) => {
    e.preventDefault();
    handleSubmit(new FormData(e.target));
  });

  await user.type(screen.getByLabelText(/email/i), '[email protected]');
  await user.type(screen.getByLabelText(/password/i), 'password123');
  await user.click(screen.getByRole('button', { name: /submit/i }));

  expect(handleSubmit).toHaveBeenCalled();
});

This test:

  • Survives refactoring (state → signals → stores)
  • Tests the contract (what users see)
  • Catches real bugs (broken onClick, validation errors)

Query Selection Priority

Most critical Testing Library skill: choosing the right query.

Priority Order

Use queries in this order (accessibility-first):

  1. getByRole - Highest priority

    • Queries by ARIA role + accessible name
    • Mirrors screen reader experience
    • Forces semantic HTML
  2. getByLabelText - Form fields

    • Finds inputs by associated <label>
    • Ensures accessible forms
  3. getByPlaceholderText - Fallback for inputs

    • Only when label not present
    • Placeholder shouldn't replace label
  4. getByText - Non-interactive content

    • Headings, paragraphs, list items
    • Content users read
  5. getByDisplayValue - Current form values

    • Inputs with pre-filled values
  6. getByAltText - Images

    • Ensures accessible images
  7. getByTitle - SVG titles, title attributes

    • Rare, when other queries unavailable
  8. getByTestId - Last resort only

    • When no other query works
    • Not user-facing

Query Variants

Three variants for every query:

getBy* - Element must exist (throws if not found)

// ✅ Use when asserting element EXISTS
const button = screen.getByRole('button', { name: /submit/i });
expect(button).toBeDisabled();

queryBy* - Returns null if not found

// ✅ Use when asserting element DOESN'T exist
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();

// ❌ WRONG - getBy throws, can't assert non-existence
expect(() => screen.getByRole('dialog')).toThrow(); // Ugly!

findBy* - Async, waits for element to appear

// ✅ Use when element appears after async operation
const message = await screen.findByText(/success/i);


Content truncated.

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,5611,368

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,0961,179

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,4101,106

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,184744

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,141682

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,292607

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.