Sunny Sachdeva
Sunny Sachdeva

Reputation: 289

Cypress: cy.click() failed because this element is detached from the DOM

I'm facing an issue with Cypress 4.7.0. Below is the error code that I'm getting while trying to automate the user creation scenario on the website automationpractice.com

The method cy.click() failed because this element is detached from the DOM.

<input type="password" class="is_required validate form-control" data-validate="isPasswd" name="passwd" id="passwd">

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

The previous command that ran was:

cy.get()

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

Common situations why this happens:

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

Code sample for the above scenario:

describe("Cypress demo script", () => {
  it("triage DOM issue", () => {
    const uuid = () => Cypress._.random(0, 1e6);
    const id = uuid();

    cy.visit("http://automationpractice.com/index.php");
    cy.wait(2000);
    cy.contains("Sign in").click();
    const email = "tester" + id + "@yopmail.com";
    cy.get("#email_create").type(email);
    cy.get("#SubmitCreate > span").click();

    cy.get("form#account-creation_form").within(($form1) => {
      cy.get("input#id_gender1").click();
      cy.get("input#customer_firstname").type("Automation");
      cy.get("input#customer_lastname").type("tester");
      cy.get("input#passwd").click({ force: true }).type("Qwerty@123");
    });
  });
});

Based on the searches, it was advised to use {force: true}, but it didn't work. Also, I tried to embed the searches within the form, it didn't work either.

Upvotes: 5

Views: 2764

Answers (1)

Paolo
Paolo

Reputation: 5441

As of Cypress version 12, there is new code (internally) that checks for elements detached from the DOM, so instead of throwing the error it now automatically does what the error message suggests and re-queries the selector.

Please see https://docs.cypress.io/guides/references/changelog#12-0-0

Additionally in this release, enhancements were made to how Cypress manages DOM element resolution to reduce the likelihood of hitting detached DOM errors due to maintaining stale DOM references. We've updated our [Retry-ability Guide[(https://docs.cypress.io/guides/core-concepts/retry-ability) with all the details if you'd like to learn more.

Upvotes: 10

Related Questions