Skip to content
Latchkey

Testing Library "Unable to find an element with the text/role"

Testing Library could not find the element your query described. Usually the UI is still loading (you used a sync getBy instead of an async findBy), the role/name is wrong, or the text is split across nodes.

What this error means

A test fails with "Unable to find an element with the text: X" (or role), and Testing Library prints the rendered DOM. The element appears in the real app - but at the moment of the query it was not present or did not match.

Jest/Vitest output
TestingLibraryElementError: Unable to find an element with the text:
Welcome back. This could be because the text is broken up by multiple
elements. ...

<body>
  <div>
    <span>Welcome</span><span>back</span>
  </div>
</body>

Common causes

Querying before async UI renders

A getBy* query runs synchronously. If the element appears after a fetch/effect, it is not there yet - you need an async findBy* that waits.

Wrong query, role, or accessible name

Querying by a role/name that does not match the rendered accessibility tree (e.g. a button with no accessible name) finds nothing.

Text split across multiple elements

Text broken into several nodes (icons, spans) defeats an exact-string getByText. A function matcher or normalization is needed.

How to fix it

Use findBy for elements that appear asynchronously

findBy* returns a promise that retries until the element shows up or times out.

component.test.tsx
// awaits the element instead of failing immediately
expect(await screen.findByText('Welcome back')).toBeInTheDocument();
// for disappearance:
await waitForElementToBeRemoved(() => screen.queryByText('Loading'));

Query the way users perceive the element

  1. Prefer getByRole(name) with the accessible name over brittle text/test-id queries.
  2. For split text, pass a function matcher to getByText.
  3. Use screen.debug() to print the DOM and see what actually rendered.

How to prevent it

  • Use findBy* for anything that renders after async work.
  • Prefer role-based queries with accessible names.
  • Give interactive elements proper labels so they are queryable.

Frequently asked questions

What causes ""Unable to find an element""?
A getBy* query runs synchronously. If the element appears after a fetch/effect, it is not there yet - you need an async findBy* that waits.
How do I fix "Unable to find an element"?
findBy* returns a promise that retries until the element shows up or times out.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card