0
0
CypressDebug / FixBeginner · 4 min read

How to Fix Detached from DOM Error in Cypress Tests

The detached from DOM error in Cypress happens when the element you want to test is removed or changed in the page before Cypress interacts with it. To fix this, avoid storing elements in variables and instead use fresh cy.get() calls before each action to ensure the element is attached to the DOM.
🔍

Why This Happens

This error occurs because Cypress tries to interact with an element that was on the page but got removed or replaced before the command runs. Web pages often update or reload parts dynamically, so the element reference Cypress holds becomes invalid or "detached" from the current page.

javascript
cy.get('#submit-button').then(($btn) => {
  // Store the button element
  const button = $btn;
});

// Later in the test
button.click(); // This causes 'detached from DOM' error if the button changed
Output
CypressError: cy.click() failed because this element is detached from the DOM.
🔧

The Fix

Instead of saving elements in variables, always use fresh cy.get() commands right before interacting with elements. This ensures Cypress works with the current version of the element attached to the DOM.

javascript
cy.get('#submit-button').click(); // Correct: fresh get before click

// Or if you need to reuse, chain commands without storing elements
cy.get('#submit-button').then(($btn) => {
  cy.wrap($btn).click();
});
Output
Test passes without 'detached from DOM' error.
🛡️

Prevention

To avoid this error in the future, follow these best practices:

  • Never store DOM elements in variables for later use; always query fresh elements.
  • Use Cypress commands chaining to keep elements in sync with the DOM.
  • Wait for page updates or animations to finish before interacting with elements using cy.wait() or cy.intercept().
  • Use cy.get() with proper selectors and retries to ensure elements are ready.
⚠️

Related Errors

Other errors similar to 'detached from DOM' include:

  • "Element is not visible": Happens when the element exists but is hidden or covered.
  • "Timed out retrying": Occurs when Cypress waits too long for an element that never appears.
  • "Cannot read property of null": Happens if you try to access properties of an element that does not exist.

Quick fixes usually involve waiting for elements properly and querying fresh elements before actions.

Key Takeaways

Always use fresh cy.get() calls before interacting with elements to avoid stale references.
Avoid storing DOM elements in variables for later use in Cypress tests.
Wait for page updates or animations to complete before interacting with elements.
Chain Cypress commands to keep elements in sync with the current DOM state.
Use proper selectors and retries to ensure elements are present and attached.