@testing-library/jest-dom: Custom Matchers for DOM Testing

@testing-library/jest-dom: Custom Matchers for DOM Testing

When you write DOM tests with React Testing Library or plain jsdom, the default Jest matchers fall short. You end up writing verbose assertions like expect(element.getAttribute('disabled')).not.toBeNull() instead of expect(button).toBeDisabled(). The @testing-library/jest-dom package solves this by extending Jest with a set of semantic DOM matchers that make tests read like specifications.

This guide covers every matcher with real examples, setup for different environments, and patterns for extending the library with your own custom matchers.

Installation and Setup

npm install --save-dev @testing-library/jest-dom

Add it to your Jest setup file so matchers are available globally:

// src/setupTests.ts
import '@testing-library/jest-dom';

Reference the file in jest.config.ts:

export default {
  setupFilesAfterFramework: ['./src/setupTests.ts'],
};

With Create React App or Vite + @vitejs/plugin-react, this is already configured out of the box.

TypeScript Support

The package ships its own type declarations. If TypeScript doesn't pick them up automatically, add the reference to your test files or tsconfig.json:

// Option 1: per-file triple-slash reference
/// <reference types="@testing-library/jest-dom" />

// Option 2: tsconfig.json
{
  "compilerOptions": {
    "types": ["@testing-library/jest-dom"]
  }
}

Presence and Visibility Matchers

toBeInTheDocument

The most common matcher — asserts that an element exists in the document:

import { render, screen } from '@testing-library/react';
import Notification from './Notification';

it('shows error message on failure', () => {
  render(<Notification type="error" message="Something went wrong" />);
  expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});

it('does not show notification when dismissed', () => {
  render(<Notification dismissed />);
  expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});

Note: use queryBy* (not getBy*) when asserting absence — getBy* throws if the element is missing.

toBeVisible

Checks that the element and all its ancestors are visible. An element is not visible if it or any ancestor has display: none, visibility: hidden, opacity: 0, or the hidden attribute:

it('hides the dropdown when closed', () => {
  render(<Dropdown isOpen={false} />);
  const menu = screen.getByRole('menu');
  expect(menu).not.toBeVisible();
});

it('shows the dropdown when open', () => {
  render(<Dropdown isOpen={true} />);
  expect(screen.getByRole('menu')).toBeVisible();
});

toBeEmptyDOMElement

Asserts the element has no visible children:

it('renders an empty container initially', () => {
  render(<ResultsContainer results={[]} />);
  expect(screen.getByTestId('results')).toBeEmptyDOMElement();
});

Form and Input Matchers

toHaveValue

Works for input, select, and textarea. Checks the current value:

it('pre-fills the email field', async () => {
  render(<ProfileForm user={{ email: 'alice@example.com' }} />);
  expect(screen.getByLabelText('Email')).toHaveValue('alice@example.com');
});

it('selects the correct option', () => {
  render(<CountrySelect defaultValue="US" />);
  expect(screen.getByRole('combobox')).toHaveValue('US');
});

// Numeric inputs return numbers
it('handles numeric input', () => {
  render(<input type="number" defaultValue={42} />);
  expect(screen.getByRole('spinbutton')).toHaveValue(42);
});

toBeDisabled / toBeEnabled

it('disables submit while loading', () => {
  render(<LoginForm isLoading />);
  expect(screen.getByRole('button', { name: /submit/i })).toBeDisabled();
});

it('enables submit when form is valid', () => {
  render(<LoginForm isValid />);
  expect(screen.getByRole('button', { name: /submit/i })).toBeEnabled();
});

These check the actual disabled state, including elements inside a disabled fieldset.

toBeRequired / toBeChecked

it('marks email field as required', () => {
  render(<SignupForm />);
  expect(screen.getByLabelText('Email')).toBeRequired();
});

it('checks the "remember me" checkbox by default', () => {
  render(<LoginForm rememberMe />);
  expect(screen.getByRole('checkbox', { name: /remember me/i })).toBeChecked();
});

toHaveFormValues

Asserts the values of all form inputs at once:

it('submits with the correct form values', () => {
  render(<ContactForm />);

  userEvent.type(screen.getByLabelText('Name'), 'Alice');
  userEvent.type(screen.getByLabelText('Email'), 'alice@example.com');
  userEvent.selectOptions(screen.getByLabelText('Subject'), 'billing');

  expect(screen.getByRole('form')).toHaveFormValues({
    name: 'Alice',
    email: 'alice@example.com',
    subject: 'billing',
  });
});

Accessibility and Attribute Matchers

toHaveAttribute

it('links open in a new tab', () => {
  render(<ExternalLink href="https://example.com" />);
  const link = screen.getByRole('link');
  expect(link).toHaveAttribute('target', '_blank');
  expect(link).toHaveAttribute('rel', 'noopener noreferrer');
});

// Check presence without value
expect(input).toHaveAttribute('autofocus');

// Use regex for partial match
expect(img).toHaveAttribute('src', expect.stringContaining('avatar'));

toHaveClass

it('applies active class to the selected tab', () => {
  render(<Tabs activeIndex={1} tabs={['Home', 'Profile']} />);
  const tabs = screen.getAllByRole('tab');
  expect(tabs[1]).toHaveClass('tab--active');
  expect(tabs[0]).not.toHaveClass('tab--active');
});

// Multiple classes — all must be present
expect(btn).toHaveClass('btn', 'btn-primary', 'btn-lg');

toHaveStyle

it('applies correct error color', () => {
  render(<StatusBadge status="error" />);
  expect(screen.getByText('Error')).toHaveStyle({ color: 'rgb(220, 53, 69)' });
});

// Partial style check
expect(modal).toHaveStyle('position: fixed');

toHaveAccessibleName / toHaveAccessibleDescription

Essential for accessibility testing:

it('icon button has accessible name', () => {
  render(<IconButton icon="close" aria-label="Close dialog" />);
  expect(screen.getByRole('button')).toHaveAccessibleName('Close dialog');
});

it('input has accessible description', () => {
  render(<PasswordInput helpText="At least 8 characters" />);
  expect(screen.getByLabelText('Password')).toHaveAccessibleDescription(
    'At least 8 characters'
  );
});

Focus Matchers

toHaveFocus

it('auto-focuses the search input', () => {
  render(<SearchModal />);
  expect(screen.getByRole('searchbox')).toHaveFocus();
});

it('moves focus to dialog on open', async () => {
  render(<App />);
  userEvent.click(screen.getByRole('button', { name: /open/i }));
  expect(screen.getByRole('dialog')).toHaveFocus();
});

Content Matchers

toHaveTextContent

it('displays the item count', () => {
  render(<CartBadge count={3} />);
  expect(screen.getByTestId('cart-badge')).toHaveTextContent('3');
});

// Partial match
expect(heading).toHaveTextContent(/welcome/i);

// Exact match
expect(price).toHaveTextContent('$29.99', { normalizeWhitespace: true });

toContainElement / toContainHTML

it('modal contains the close button', () => {
  render(<Modal />);
  const modal = screen.getByRole('dialog');
  const closeBtn = screen.getByRole('button', { name: /close/i });
  expect(modal).toContainElement(closeBtn);
});

Extending with Custom Matchers

For domain-specific assertions, extend expect directly:

// src/testUtils/matchers.ts
import { expect } from '@jest/globals';

expect.extend({
  toBeValidEmail(received: string) {
    const pass = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(received);
    return {
      pass,
      message: () =>
        pass
          ? `Expected "${received}" not to be a valid email`
          : `Expected "${received}" to be a valid email`,
    };
  },
  toHaveLoadingState(element: HTMLElement) {
    const pass =
      element.getAttribute('aria-busy') === 'true' ||
      element.classList.contains('loading');
    return {
      pass,
      message: () =>
        pass
          ? `Expected element not to have loading state`
          : `Expected element to have loading state (aria-busy="true" or .loading class)`,
    };
  },
});

// Type augmentation for TypeScript
declare module '@jest/globals' {
  interface Matchers<R> {
    toBeValidEmail(): R;
    toHaveLoadingState(): R;
  }
}

Import your custom matchers in setupTests.ts and they're available everywhere:

import '@testing-library/jest-dom';
import './testUtils/matchers';

Summary

@testing-library/jest-dom transforms verbose DOM assertions into readable specifications. The full set covers presence (toBeInTheDocument), visibility (toBeVisible), form state (toHaveValue, toBeDisabled, toBeChecked), attributes (toHaveAttribute, toHaveClass), accessibility (toHaveAccessibleName), focus, and content. Combined with React Testing Library's queries, these matchers let you write tests that describe user-visible behavior without digging into implementation details. When the built-in matchers don't cover a domain-specific assertion, expect.extend lets you add your own with the same clean API.

Read more

Start now free