kosto
kosto

Reputation: 21

Cypress and unstable DOM

I am using cypress for some e2e tests on a react application and I am having problems clicking on an element.

I have this simple script:

it('can bookmark/unbookmark the posting', () => {
    cy.visit(pdfPosting.url)
      .wait(1000)
      .contains('Save')
      .should('be.visible')
      .click();

    cy.visit('/jobs/jobbox')
      .contains(pdfPosting.title)
      .should('be.visible');

    cy.visit(pdfPosting.url)
      .wait(1000)
      .contains('Saved')
      .should('be.visible')
      .click();

    cy.visit('/jobs/jobbox')
      .findByText(pdfPosting.title)
      .should('not.exist');
    }
  });

My problem starts because the Save and Saved buttons are inside a react component that is refreshed several times, for unknown reasons, when page is loaded. Test fails because sometimes the component is refreshed between the contains and the click on the button.

Right now the only way to workaround this problem was adding the waits you see on the test, but I really hate this hack.

First thing I tried to do, was catching the error and retrying the contains.should.click block, but cypress does not allows this (https://docs.cypress.io/guides/core-concepts/conditional-testing.html#Error-Recovery) and ever worst the workarounds proposed on this article are not working to me (or I do not know how to do it)

I also tried to work with events (https://docs.cypress.io/api/events/catalog-of-events.html#Uncaught-Exceptions) but I could not found any that I could use to retry only a part of the code and continue with the execution of the test.

I tried to talk with developers, if they could fix the refresh issue, but the short story is that they won't. Final user does not realize about this refresh on the component and there is not budget to investigate the problem.

Also I was discussing with developers if we could add something, somewhere, to indicate that the loading of the component had finished, but, again, this seems to be not possible. They cant not grant that loading of the component has finished because they do not know where these refreshes come from.

Do you know how I can use cypress to handle this situation?

Upvotes: 2

Views: 2430

Answers (1)

arturvt
arturvt

Reputation: 781

It's a bad practice use waits in cypress. I'd suggest use the playground

https://docs.cypress.io/guides/core-concepts/test-runner.html#Selector-Playground

to find your items. Try to follow the Uniqueness principle and use the cy.get('[data-test-selector=you-selector']); instead of wait. It'll wait for you.

For example, visit and cy.get the title page.

Also, if you have animations, it might cause DOM issues with back and forth. If you remove them it'll be faster and more stable.

Upvotes: 1

Related Questions