How to Fix Element Not Found Error in Cypress Tests
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.
cy.get('#submit-button').click();
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.
cy.get('#submit-button', { timeout: 10000 }).should('be.visible').click();
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.