Sub topic 7
Readable assertions with jest-dom
This chapter assumes you can write React function components, know test and expect in Jest or Vitest, and can run a basic Testing Library query such as screen.getByRole. It covers the matchers that @testing-library/jest-dom adds, and how to choose among them.
Why plain assertions fall short
A query returns a DOM node. With only the built-in matchers, you have to reach into that node's properties to check it:
expect(button.disabled).toBe(true);
expect(heading.textContent).toBe('Hello, Ada');
expect(document.body.contains(heading)).toBe(true);These checks work, but they describe DOM properties, not what a user sees. A failure prints expected true, received false, which says nothing about the element. jest-dom adds matchers that read like the behavior and print the element's HTML when they fail.
Registering the matchers
Import jest-dom once in a setup file, and every test gets the matchers.
// jest.setup.js (referenced from setupFilesAfterEach in the Jest config)
import '@testing-library/jest-dom';
// Vitest equivalent in a setup file:
// import '@testing-library/jest-dom/vitest';In Vitest, list this file under setupFiles in the config. If a matcher is reported as "not a function", the setup file is usually not being loaded.
The matchers you will use most
| Matcher | Passes when |
|---|---|
| `toBeInTheDocument()` | The element is attached to the document. |
| `toBeVisible()` | The element and its ancestors are not hidden by `display: none`, `visibility: hidden`, `opacity: 0`, or the `hidden` attribute. |
| `toBeDisabled()` / `toBeEnabled()` | The form control is disabled or enabled, including through a disabled `fieldset`. |
| `toHaveTextContent(text)` | The element's text matches a string (substring) or a regular expression. |
| `toHaveValue(value)` | An input, select, or textarea holds the value. |
| `toBeChecked()` | A checkbox, radio, or `role="checkbox"` element is checked. |
| `toHaveAttribute(name, value?)` | The attribute exists, optionally with that value. |
| `toHaveAccessibleName(name)` | The computed accessible name matches. |
| `toHaveFocus()` | The element is the active element. |
A worked example
The component below shows a message and a button whose state depends on props.
// SaveBar.jsx
export function SaveBar({ dirty, saving }) {
return (
<div>
<input aria-label="Title" defaultValue="Draft" />
{saving && <p role="status">Saving...</p>}
<button disabled={!dirty || saving}>Save</button>
</div>
);
}
// SaveBar.test.jsx
import { render, screen } from '@testing-library/react';
import { SaveBar } from './SaveBar';
test('disables Save until the form is dirty', () => {
const { rerender } = render(<SaveBar dirty={false} saving={false} />);
const save = screen.getByRole('button', { name: 'Save' });
expect(save).toBeDisabled();
expect(screen.getByLabelText('Title')).toHaveValue('Draft');
expect(screen.queryByRole('status')).not.toBeInTheDocument();
rerender(<SaveBar dirty saving={false} />);
expect(save).toBeEnabled();
rerender(<SaveBar dirty saving />);
expect(screen.getByRole('status')).toHaveTextContent('Saving');
expect(save).toBeDisabled();
});Each assertion names a user-visible fact. If toBeDisabled fails, the output includes the button's markup, so you can see the actual state.
Absence and negation
To assert that something is not rendered, use queryBy with .not.toBeInTheDocument(), as shown above. A getBy query would throw before the assertion runs.
Keep these two cases apart:
not.toBeInTheDocument()means the element is not in the DOM at all.not.toBeVisible()means the element is in the DOM but hidden.
Use whichever matches how your component hides content. A conditional render ({open && <Panel />}) removes the node. A CSS class or hidden attribute keeps it.
Common errors
- Using
toBeVisiblefor layout. jsdom does not compute layout or load your stylesheets, so a class that hides an element through an external CSS file is not detected. Inline styles and thehiddenattribute are detected. - Matching the wrong text.
toHaveTextContent('Saving')is a substring match, so it also passes for "Saving failed". Use a regular expression with anchors, such as/^Saving\.\.\.$/, orgetByTextwith an exact string when exactness matters. - Asserting on a detached element. If React replaces a node, a variable holding the old node may no longer be in the document. Re-query after the change when the element could be recreated.
- Checking
toBeDisabledon a non-control. Adivwitharia-disabled="true"is not disabled in the DOM sense. UsetoHaveAttribute('aria-disabled', 'true')for it.
Exercise
A test uses expect(screen.getByText('Error')).not.toBeInTheDocument() to check that no error message is shown. The test fails even though the message is absent. Why, and how do you fix it?
Show answer
getByText throws when it finds no match, so the test fails before the matcher runs. Replace it with screen.queryByText('Error'), which returns null when nothing matches, and keep .not.toBeInTheDocument().
Exercise
A modal is hidden with style="display: none" but stays in the DOM. Which assertion confirms that the user cannot see it: not.toBeInTheDocument() or not.toBeVisible()?
Show answer
not.toBeVisible(). The element is still in the document, so not.toBeInTheDocument() would fail. toBeVisible checks the inline display: none.