These matchers allow you to assert whether an element contains descendants using Testing Library queries. They are useful when toBeInTheDocument is not specific enough, as they scope the query to a specific part of the DOM and produce clear pass/fail results instead of throwing when an element is absent.
Matcher Logic
| Matcher | 0 matches | 1 match | >1 matches |
|---|
toContainOneBy... | ❌ | ✅ | ❌ |
not.toContainOneBy... | ✅ | ❌ | ✅ |
toContainAnyBy... | ❌ | ✅ | ✅ |
not.toContainAnyBy... | ✅ | ❌ | ❌ |
Supported Queries
All query options supported by @testing-library/dom (e.g. exact, name, selector) are passed through to the underlying query.
toContainAnyByAltText / toContainOneByAltTexttoContainAnyByDisplayValue / toContainOneByDisplayValuetoContainAnyByLabelText / toContainOneByLabelTexttoContainAnyByPlaceholderText / toContainOneByPlaceholderTexttoContainAnyByRole / toContainOneByRoletoContainAnyByTestId / toContainOneByTestIdtoContainAnyByText / toContainOneByTexttoContainAnyByTitle / toContainOneByTitle
Using document.body as the container is equivalent to screen.getBy*.
const results = getByRole('region', {name: 'search results'})
const related = getByRole('region', {name: 'related articles'})
// passes: one or more listitem elements in the results section
expect(results).toContainAnyByRole('listitem')
// passes: exactly one heading in the related section
expect(related).toContainOneByRole('heading', {name: 'Related article'})
// fails: there are two listitems, not one
expect(results).not.toContainOneByRole('listitem')
// fails: no heading in the results section
expect(related).not.toContainAnyByRole('heading')