Solving The Element Is Detached From DOM Error In Cypress

A video of a page refreshing and breaking a Cypress test and several possible solutions.

Many people complain about the dreaded "Element is detached from DOM" error in Cypress, see #7306. I have recorded the video showing the problem and the possible solutions below.

Tip: I have described previously this particular scenario in the blog post When Can the Test Submit a Form? which is a part of my series of blog posts about test flake.

When writing E2E tests, please consider what the application is doing. If the application is still performing an action, tell the test to "wait" for the action to complete. Otherwise the application might suddenly change, breaking the test. The "element is detached from DOM" is a sign of a problem, not the problem itself! There is a variety of ways the test can observe the application and wait for it to be ready. You can observe the DOM itself, the network traffic, listen for events, even reach into the code to spy on method calls.

A good pattern is to alternate test commands and assertions, relying on the built-in retry-ability to wait for the application to finish updating. This way the test never waits longer than necessary.

6 // command
// application starts doing something
// now the test should wait for the app
// before calling another command
cy.get('...').should('have.class', 'ready')
// execute the next test command

And if everything fails, if there is no observable application property to wait for - then add the cy.wait(xxx) command to wait for a second or two. I mean, if it fixes the detached element problem and the test becomes stable, why not?