DEV Community

Alex Spinov
Alex Spinov

Posted on

Testing Library Has a Free API You Should Know About

Testing Library encourages testing your components the way users interact with them — by text content, role, and label, not implementation details like class names or component structure.

Why Testing Library Changes Unit Testing

A team's React tests broke every time they refactored a component — even when behavior was unchanged. Tests were coupled to implementation (CSS classes, div structure). Testing Library tests by what users see — refactor freely without breaking tests.

Key Features:

  • User-Centric — Query by text, role, label — not class names
  • Framework Support — React, Vue, Angular, Svelte, Preact
  • Lightweight — Simple API, minimal setup
  • Accessible — Encourages accessible component design
  • Jest/Vitest Compatible — Works with any test runner

Quick Start

npm install -D @testing-library/react @testing-library/jest-dom
Enter fullscreen mode Exit fullscreen mode
import { render, screen, fireEvent } from "@testing-library/react"
import { Counter } from "./Counter"

test("increments counter on click", () => {
  render(<Counter />)
  const button = screen.getByRole("button", { name: /increment/i })
  fireEvent.click(button)
  expect(screen.getByText("Count: 1")).toBeInTheDocument()
})
Enter fullscreen mode Exit fullscreen mode

User Event (Realistic Interactions)

import userEvent from "@testing-library/user-event"

test("submits form", async () => {
  render(<LoginForm />)
  await userEvent.type(screen.getByLabelText("Email"), "test@example.com")
  await userEvent.type(screen.getByLabelText("Password"), "secret")
  await userEvent.click(screen.getByRole("button", { name: /log in/i }))
  expect(screen.getByText("Welcome!")).toBeInTheDocument()
})
Enter fullscreen mode Exit fullscreen mode

Why Choose Testing Library

  1. Refactor-proof — tests don't break on implementation changes
  2. User perspective — tests verify what users actually see
  3. Better accessibility — encourages semantic HTML

Check out Testing Library docs to get started.


Building tested apps? Check out my Apify actors or email spinov001@gmail.com for custom solutions.

Top comments (0)