1
votes

I want to do a conditional testing in cypress. The situation is, that I want to achieve this:

If an alert modal window is present on the page , then click the YES button, otherwise do nothing.

The structure of the alert is something like:

<div class="swal2-container">
<h2>You are about to leave this page</h2>
<button type="button" class="swal2-confirm">Yes</button>
</div>

I tried it this way:

cy.get('body').then((body) => {
        if (body.find('button.swal2-confirm').length > 0) {
            cy.get('button.swal2-confirm').contains('Yes').click();
        }
    });

but this does nothing, it doesn't click the button. In test runner I just see as an output get ... body and it is skipped.

i also tried to replace body with $body with no luck.

1
When you are searching for the Yes button, Is the action that was suppose to produce that modal, has it completely executed? To debug this behaviour apply a cy.wait(4000) before your code and do the action that produces the modal window window. Your code looks correct. - Alapan Das
yes, the alert is there, I see it in test runner. It just doesn't click on the button so the alert stays there and then the next step fails, because the alert is still there - Darksymphony
can you add the html screenshot of the element to the question? - Alapan Das
wait man, I applied your advice and added cy.wait, and now it works! Strange, because in test runner I see that alert, but maybe it had a little time to click. Seems it is solved now, thank you for your advice, helpful as always - Darksymphony

1 Answers

1
votes

It's a little more code, but a recursive function allows you to exit without failure (the do-nothing part).

You may need to adjust the number of attempts and the wait(200). Essentially the smaller the wait, the more attempts you may need.

At 20 attempts & 200ms wait, it's equivalent to { timeout: 4000 } on a Cypress command.

function ifModal(attempt = 0) {

  if (attempt > 20) return;  // do nothing

  if (Cypress.$('button.swal2-confirm').length > 0) {

    cy.contains('button.swal2-confirm', 'Yes').click();
    return;                 // done

  } else {

    cy.wait(200).then(() => {  
      ifModal(++attempt)      // next attempt
    })

  }
});  

ifModal();