0
0
CypressDebug / FixBeginner · 4 min read

How to Fix Element Not Found Error in Cypress Tests

The element not found error in Cypress happens when the test tries to find a page element that does not exist or is not yet visible. To fix it, ensure your cy.get() selector is correct and add proper waiting or retries so Cypress finds the element after it appears.
🔍

Why This Happens

This error occurs because Cypress cannot find the element you want to interact with. It might be due to a wrong CSS selector, the element not being rendered yet, or the element being hidden or removed from the page.

javascript
cy.get('#submit-button').click();
Output
CypressError: Timed out retrying: Expected to find element: '#submit-button', but never found it.
🔧

The Fix

Check that your selector matches the actual element in the page. Use Cypress commands like cy.contains() or more specific selectors. Add cy.wait() or use cy.get() with built-in retry to wait for the element to appear before interacting.

javascript
cy.get('#submit-button', { timeout: 10000 }).should('be.visible').click();
Output
Test passes when the '#submit-button' is found and clicked successfully.
🛡️

Prevention

Always use stable and unique selectors like data attributes (data-cy) instead of classes or IDs that may change. Avoid hard-coded waits; rely on Cypress's automatic retries and assertions to wait for elements. Regularly update selectors if the UI changes.

⚠️

Related Errors

Other common errors include element is detached from the DOM which means the element was removed before interaction, and element not visible which means the element exists but is hidden. Fix these by ensuring elements are stable and visible before acting on them.

Key Takeaways

Use correct and stable selectors to find elements reliably.
Leverage Cypress's automatic retries and assertions to wait for elements.
Avoid fixed waits; prefer conditional waits like .should('be.visible').
Update selectors when UI changes to prevent element not found errors.
Check for element visibility and presence before interacting.