ManInBlue
ManInBlue

Reputation: 15

In Cypress how can I force cy.get to wait for page content to change?

I'm new to Cypress and am writing a test for a React webpage that checks that when a button is clicked, the page heading changes (I know this might not be the most useful check).

To be clear, the button click does not cause a new webpage to be loaded, it just causes the current page's content to change.

Below is an example snippet similar to my actual Cypress code, including the button click and the subsequent expectation.

cy.get('[data-testId="<button ID>"]')
    .click();

cy.get('body h2')
   .contains('<some text>');

My problem is that if an h2 header exists prior to the button click, Cypress is getting that header instead of the h2 header that exists after the button click.

Is it possible to force Cypress to wait until the page is updated? Or to retry the get/contains steps until the expectation is met? Or am I am just making an obvious rookie mistake?

Upvotes: 0

Views: 1476

Answers (1)

Rosen Mihaylov
Rosen Mihaylov

Reputation: 1425

If your selector on the element is correct - you can use cy.should. It retries until the condition is fulfilled or the predetermined timeout is up:

cy.get('[data-testId="<button ID>"]')
    .click();

cy.get('body h2')
   .should('contain', '<some text>');

This works if the page isn`t reloading after the action. If it is you should add some rendertime asserion like:

cy.get('[data-testId="<button ID>"]')
    .click();

cy.get('body h2')
   .should('not.exist') //Checks if the page starts reloading and the initial element has dissapeared.

cy.get('body h2')
   .should('contain', '<some text>');

Upvotes: 1

Related Questions