Error Message

error: cy… () failed because the element you are chaining off of has become detached or removed from the dom

error.png


Reason

If there is a re-rendering in the process, the previous element may be found by Cypress. Such problems are particularly likely to occur on pages using React.

The actual problem is that an element has been re-rendered during the process, but the keyword for position is the same (assumed to be Element A). Element A already existed before Command L2 was executed, Command L1 caused Element A to be re-rendered, but Command L1 was delayed for some reasons, and when Command L2 was being executed, Element A was re-rendered and was judged to be detached.


Solution

Many Cypress users have given feedback about this problem: https://github.com/cypress-io/cypress/issues/7306

When You Need to Interact With The Element

The easiest way is use {force:true}:

cy.get('element').click({force:true})

Also, you can fix it by anther way ( I will show you below ).


When You Need to Assert The Element

The solution to the problem is to make sure that Element A has been already re-rendered when Command L2 is being executed:

  • Compare whether the value of Element A attributes have changed.

  • Determine that Element A state has been stable.

function ElementExist(element, number){
cy.waitUntil(() => cy.get(element).then(($el) => $el.length >= number))
}

// All users are loaded (assuming a total of 5) as the re-rendering is complete and the element is stable
ElementExist('.user-item', 5)

Tips:

  • You can observe the rendering of the DOM by breakpoints.
    breakpoint.png

Good News

The development team will soon fix this issue, probably done in Cypress 10.x

https://github.com/cypress-io/cypress/issues/7306
fix_detached.png