Element Not Found in DOM Test
Error message
TestingLibraryElementError: Unable to find an element by role/text
Quick summary
The test tries to find an element (by role, text, testId) but it doesn't exist in the rendered component. The element might not be rendered or the query is wrong.
Why this happens
The element isn't rendered — conditional rendering hides it.
The query text or role doesn't match the rendered element.
The element is rendered asynchronously and the test didn't wait.
The component wasn't rendered with the right props to show the element.
Minimal example
test('shows welcome', () => {
render(<App loggedIn={false} />);
// Welcome message only shows when loggedIn is true
expect(screen.getByText('Welcome')).toBeInTheDocument(); // not found
});test('shows welcome', () => {
render(<App loggedIn={true} />);
expect(screen.getByText('Welcome')).toBeInTheDocument(); // found
});Provide the correct props so the element is rendered, or fix the query to match.
How to diagnose
Use screen.debug() to print the rendered HTML and see what's actually there.
Check if the element is conditionally rendered and the condition isn't met.
For async rendering, use waitFor or findBy queries (async versions of getBy).
Verify the query matches — check role, text, testId spelling.
How to fix
Fix the query to match the actual rendered element.
Provide the right props to trigger conditional rendering.
Use findByText/findbyRole (async) for elements that appear after async operations.
Wrap in waitFor() if the element appears after a state update.
How to prevent
Use screen.debug() during development to see the rendered output.
Prefer findBy* (async) over getBy* for async-rendered elements.
Query by role and accessible name for robust queries.
Related Resources
Related Glossary
Related Lessons
- React Testing
Testing React components.