Assertions & Matchers
Use jest-dom matchers for DOM state, visibility, forms, and accessibility.
jest-dom Setup
Import @testing-library/jest-dom once in setup file extends expect with DOM matchers. Vitest: import @testing-library/jest-dom/vitest.
Matchers improve failure messages compared to raw element property checks.
import "@testing-library/jest-dom";
expect(button).toBeEnabled();
expect(input).toHaveValue("ada@example.com");Text Content
toHaveTextContent supports string or regex; normalizes whitespace. toHaveAccessibleName checks computed accessible name for roles.
Prefer visible text assertions over textContent including hidden nodes.
expect(screen.getByRole("status")).toHaveTextContent(/saved/i);
expect(link).toHaveAccessibleName("Read more about testing");Classes and Attributes
toHaveClass accepts string or array; toHaveAttribute checks aria-* and data-*; toHaveStyle for inline styles. Avoid asserting implementation CSS classes users do not perceive.
Assert aria-expanded, aria-invalid for interactive widget states.
expect(dialog).toHaveAttribute("aria-modal", "true");
expect(field).toHaveClass("is-invalid");Visibility and Presence
toBeInTheDocument attached to DOM; toBeVisible checks CSS visibility not hidden and has layout. toBeDisabled, toBeRequired, toBeChecked for form controls.
not.toBeInTheDocument for removed elements; queryBy + expect not for absence.
- toHaveFocus after tab navigation keyboard tests
- toHaveFormValues for entire form snapshot of control values
- toHaveErrorMessage links input to aria-errormessage node
expect(screen.getByRole("button")).toBeVisible();
expect(screen.queryByText("Deleted")).not.toBeInTheDocument();Combining Matchers
Chain multiple expects on same element for readable spec. Soft assertion pattern not native—use multiple expects sequentially.
Custom matchers rare—jest-dom covers most DOM needs.
- Match accessible description with toHaveAccessibleDescription
- Document matcher choice in team testing guide
- Failure diff shows expected vs received HTML snippet