Sub topic 7
Readable assertions with jest-dom
This chapter assumes you can write a basic React Testing Library test with render, screen, and getBy queries. It also assumes you know Jest or Vitest well enough to use expect, and that you know how HTML attributes like disabled, hidden, and aria-invalid work.
Why jest-dom exists
A plain Jest assertion can check a DOM element, but the failure message is poor. Compare these two lines:
expect(button.disabled).toBe(true);
expect(button).toBeDisabled();Both pass and fail in the same cases for a simple button. When the first one fails, you read expected: true, received: false. When the second fails, jest-dom prints the element's HTML and says what it expected. The second line also names the user-visible state, not a DOM property.
jest-dom is a set of custom matchers for DOM nodes. You register it once in a setup file. The matchers then work in every test file.
// jest.setup.js (referenced from setupFilesAfterEnv in the Jest config)
import '@testing-library/jest-dom';
// Vitest equivalent in a setup file:
// import '@testing-library/jest-dom/vitest';The matchers only accept DOM elements. If you pass null or a string, they throw a clear error, which is useful. It tells you a query returned nothing, or that you passed the wrong value.
Matchers grouped by what they check
Most of the matchers fall into a few groups. The table lists the ones you will use most.
| Question | Matcher | Notes |
|---|---|---|
| Is it in the document? | `toBeInTheDocument()` | Fails for detached elements. |
| Can a user see it? | `toBeVisible()` | Checks `display`, `visibility`, `opacity`, and the `hidden` attribute, up the ancestor chain. |
| Is it interactive? | `toBeDisabled()`, `toBeEnabled()` | `toBeDisabled` is also true for children of a disabled `fieldset`. |
| What text does it show? | `toHaveTextContent()` | Accepts a string (substring match) or a regular expression. |
| What is the field's value? | `toHaveValue()`, `toHaveFormValues()` | `toHaveValue` returns a number for `type="number"`. |
| Is it checked? | `toBeChecked()`, `toBePartiallyChecked()` | Works for checkboxes, radios, and ARIA roles such as `switch`. |
| Is it valid? | `toBeValid()`, `toBeInvalid()`, `toBeRequired()` | Looks at `aria-invalid` and the browser's `checkValidity()`. |
| Is it focused? | `toHaveFocus()` | Compares with `document.activeElement`. |
| What does assistive technology see? | `toHaveAccessibleName()`, `toHaveAccessibleDescription()` | Prefer these to checking `aria-label` directly. |
| What attributes does it have? | `toHaveAttribute()`, `toHaveClass()`, `toHaveStyle()` | Use sparingly, see the pitfalls below. |
A worked example
This component has several states that a user can notice: an error message, an invalid field, a disabled button, and a checked box.
// Subscribe.jsx
import { useState } from 'react';
export function Subscribe() {
const [email, setEmail] = useState('');
const [agreed, setAgreed] = useState(false);
const hasInput = email !== '';
const valid = email.includes('@');
return (
<form>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
required
aria-invalid={hasInput && !valid}
onChange={(e) => setEmail(e.target.value)}
/>
{hasInput && !valid && <p role="alert">Enter a valid email address</p>}
<label>
<input
type="checkbox"
checked={agreed}
onChange={(e) => setAgreed(e.target.checked)}
/>
I agree to the terms
</label>
<button type="submit" disabled={!valid || !agreed}>
Subscribe
</button>
</form>
);
}// Subscribe.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Subscribe } from './Subscribe';
test('guides the user to a submittable form', async () => {
const user = userEvent.setup();
render(<Subscribe />);
const email = screen.getByLabelText('Email');
const terms = screen.getByRole('checkbox', { name: /agree/i });
const submit = screen.getByRole('button', { name: 'Subscribe' });
expect(email).toBeRequired();
expect(submit).toBeDisabled();
expect(terms).not.toBeChecked();
await user.type(email, 'ada');
expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid email');
expect(email).toBeInvalid();
await user.type(email, '@example.com');
expect(email).toHaveValue('[email protected]');
expect(email).toBeValid();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(submit).toBeDisabled();
await user.click(terms);
expect(terms).toBeChecked();
expect(submit).toBeEnabled();
});Read the assertions aloud and they describe the screen: "the email is required", "the submit button is disabled", "the alert has text content...". A reader does not need to know which props or state variables the component uses.
Asserting that something is absent
.not inverts any matcher, but absence needs care. getBy throws when it finds nothing, so the test fails before the assertion runs. Use queryBy, which returns null:
expect(screen.queryByRole('alert')).not.toBeInTheDocument();The reverse mistake is also common. Writing expect(screen.getByRole('button')).toBeInTheDocument() works, but the assertion adds nothing, because getBy already throws if the element is missing. Keep toBeInTheDocument() for queryBy or findBy results, where you want the test to read as a statement. It is fine to leave it on getBy when the line is the whole point of the test.
In the document versus visible
toBeInTheDocument() and toBeVisible() answer different questions. An element can be in the DOM but hidden from the user.
// Banner.jsx
export function Banner({ unread }) {
return (
<section aria-label="Notifications">
<a href="/inbox" className="link link--active">
Inbox ({unread} unread)
</a>
<p hidden>Sync paused</p>
</section>
);
}// Banner.test.jsx
import { render, screen } from '@testing-library/react';
import { Banner } from './Banner';
test('shows the unread count and keeps the sync notice hidden', () => {
render(<Banner unread={3} />);
const link = screen.getByRole('link', { name: /inbox/i });
expect(link).toHaveAttribute('href', '/inbox');
expect(link).toHaveTextContent(/3 unread/);
expect(link).toHaveClass('link--active');
const notice = screen.getByText('Sync paused');
expect(notice).toBeInTheDocument();
expect(notice).not.toBeVisible();
});Here getByText finds the hidden paragraph, because text queries do not filter by visibility. Role queries do: getByRole('paragraph') style lookups skip elements that are hidden from the accessibility tree, unless you pass { hidden: true }.
The diagram shows how to choose a matcher for the question you are asking.
Gotchas and common errors
toHaveTextContent matches substrings
A string argument matches if the element's normalized text contains it. toHaveTextContent('Count: 1') also passes for Count: 10. To require an exact match, use a regular expression anchored at both ends, such as /^Count: 1$/. jest-dom normalizes whitespace first, so extra spaces and line breaks do not matter.
toBeVisible depends on what jsdom knows
jsdom does not load your CSS files. A class that hides an element through a stylesheet will not make toBeVisible() fail, because jsdom never sees the rule. Inline styles, the hidden attribute, and display: none set in JavaScript do work. If your component hides content with a CSS class, assert on the state the user relies on, such as aria-expanded, instead.
toHaveClass and toHaveStyle test implementation
A class name is rarely something a user notices. Prefer asserting the state that the class represents, for example toBeChecked() or toHaveAccessibleName(). Use toHaveClass when the class is the contract, such as a utility class provided by a design system. toHaveStyle reads the computed style, so it only sees styles that jsdom can apply from inline styles or injected <style> elements.
toHaveValue returns typed values
For type="number" inputs, the value is a number, so toHaveValue('5') fails and toHaveValue(5) passes. A multi-select returns an array. An empty text input has the value '', not null.
Validity has two sources
toBeInvalid() is true when the element has an aria-invalid attribute that is not "false", or when checkValidity() returns false. A required empty field is therefore invalid from the first render. If you only mean "the app shows an error", assert on the error message instead.
Matchers are not auto-retrying
expect(...).toBeVisible() checks once. If the element appears later, use await screen.findBy... to get the element first, or wrap the assertion in waitFor. A later chapter covers this in detail.
Exercise
A test needs to check that a "Saved" message is not shown before the user clicks Save. Why does expect(screen.getByText('Saved')).not.toBeInTheDocument() fail, and what should you write instead?
Show answer
getByText throws an error when it finds no match, so the test fails before .not.toBeInTheDocument() runs. Use queryByText, which returns null for a missing element: expect(screen.queryByText('Saved')).not.toBeInTheDocument().
Exercise
An input has type="number" and the user typed 42. Write the assertion for its value, then explain why toHaveValue('42') would fail.
Show answer
expect(input).toHaveValue(42). For type="number" inputs, jest-dom returns the value as a number, and toHaveValue compares with strict equality, so the string '42' does not match.
Exercise
A panel is hidden by a CSS class defined in a .css file. Your test asserts expect(panel).not.toBeVisible() and it never passes. What is the likely cause, and what is a better assertion?
Show answer
jsdom does not load the stylesheet, so it never applies the hiding rule and the panel counts as visible. Assert on state the component exposes, such as aria-expanded="false" on the toggle button, or render the panel conditionally and use queryBy with not.toBeInTheDocument().