testing-library / cypress-testing-library

🐅 Simple and complete custom Cypress commands and utilities that encourage good testing practices.
http://npm.im/@testing-library/cypress
MIT License
1.8k stars 152 forks source link

Getting "`cy.click()` failed because this element is detached from the DOM" for an element retrieved with findByRole #222

Closed Belco90 closed 2 years ago

Belco90 commented 2 years ago

Relevant code or config

This is my test

it('should display custom 404 page when not found', () => {
  cy.visit('/not-existing-page', { failOnStatusCode: false })

  cy.title().should('equal', '404 - Not Found | Octoclairvoyant')

  cy.findByRole('heading', {
    name: 'This page could not be found.',
  }).should('exist')

  cy.findByText('Octoclairvoyant cannot divine the page you wanted.').should(
    'exist'
  )

  cy.findByRole('main').within(() => {
    cy.findByRole('img')
      .should('have.attr', 'src')
      .and('contain', 'mascot-icon')
  })

  cy.findByRole('link', { name: /go to comparator/i }).click()
  cy.url().should('equal', `${Cypress.config().baseUrl}/comparator`)

  cy.go('back')

  cy.findByRole('link', { name: 'Or go to homepage' }).click()
  cy.url().should('equal', `${Cypress.config().baseUrl}/`)
})

What you did:

Upgraded some dependencies

What happened:

The test was working correctly. After upgrading to React v18, it started being flaky. After upgrading to TS 4.7, it always fails.

The following error is displayed:

CypressError: Timed out retrying after 4050ms: cy.click() failed because this element is detached from the DOM.

<a class="chakra-link css-1h93v8h" href="/">Or go t...</a>

Cypress requires elements be attached in the DOM to interact with them.

The previous command that ran was:

cy.findByRole()

This DOM element likely became detached somewhere between the previous and current command.

Common situations why this happens:

  • Your JS framework re-rendered asynchronously
  • Your app code reacted to an event firing and removed the element

You typically need to re-query for the element or add 'guards' which delay Cypress from running new commands.

Reproduction repository:

https://github.com/octoclairvoyant/octoclairvoyant-webapp/pull/944

Problem description:

The test is always failing at trying to click in an element retrieved with cy.findByRole

Suggested solution:

No idea

Belco90 commented 2 years ago

I'm able to reproduce the issue with Cypress built-in utils, so this is not an issue from cypress-testing-library in particular.

VirtuaBoza commented 1 year ago

If the issue is with Cypress, do you know if there is a related issue in the Cypress GH? I couldn't find one, and I'm experiencing a similar problem.

dwjohnston commented 2 months ago

Worth mentioning this thread here: https://github.com/cypress-io/cypress/issues/7306