How can I fix an issue in Cypress where an element becomes detached from the DOM during test execution?

Cypress throws the following error:

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

I’m trying to run the test block below, but it fails intermittently, likely due to re-renders.

I’ve read that using Cypress guards (like re-querying or adding waits) might help, but I’m not sure how to apply them properly.

js
Copy
Edit
it('Add-Income', () => {
  cy.get('.add_btn').click();
  cy.get(':nth-child(1) > .input_container > input').type('45000');
  cy.get(':nth-child(2) > select').select('4');
  cy.get(':nth-child(3) > select').select('32');
  cy.get(':nth-child(4) > .input_container > input')
    .invoke('removeAttr', 'type')
    .type('12-12-1990{enter}');
  cy.get('.title > span').click({ force: true });
});

it('Add-Expenditure', () => {
  cy.get('.add_btn').click();
  cy.get('.overlay_card > :nth-child(4)').click();
  cy.get(':nth-child(1) > .input_container > input').type('45000');
  cy.get(':nth-child(2) > select').select('4');
  cy.get(':nth-child(3) > select').select('32');
  cy.get(':nth-child(4) > .input_container > input')
    .invoke('removeAttr', 'type')
    .type('12-12-1990{enter}');
});

What’s the best way to apply Cypress guards in this scenario to avoid detached DOM errors?

Should I use should(‘be.visible’), wait(), or something else?