Darksymphony
Darksymphony

Reputation: 2683

Cypress conditional button click

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.

Upvotes: 3

Views: 3441

Answers (3)

AliF50
AliF50

Reputation: 18809

Here is a generic function, inspired from Fody.

// !! Add the command
Cypress.Commands.add('redoCommandUntilConditionIsMet', ({
  condition,
  command, 
  maxAttempts = 20, 
  waitBeforeRetry = 1_000,
  waitForCondition = 200,
}) => {
    const redoCommandUntilConditionIsMet = (attempt = 0) => {
      if (attempt > maxAttempts) {
        return;
      }

      cy.wait(waitForCondition);

      if (condition()) {
        return;
      }

      command();

      cy.wait(waitBeforeRetry).then(() => redoCommandUntilConditionIsMet(++attempt));
    };
    redoCommandUntilConditionIsMet();
  }
});

And then can just do and can be re-used whenever required:

cy.redoCommandUntilConditionIsMet({
  condition: () => Cypress.$('button.swal2-confirm').length === 0,
  command: () => cy.contains('button.swal2-confirm', 'Yes').click(),
});

Upvotes: 0

shariq naeem
shariq naeem

Reputation: 11

You can also try the below code. .includes() is a jQuery function and I'm using it here for having text in the body.

cy.get('body').then(($body) => { 
     if ($body.includes('You are about to leave this page')) { 
          cy.get('button.swal2-confirm').contains('Yes').click(); 
     } 
});

Upvotes: 1

Fody
Fody

Reputation: 31904

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();

Upvotes: 4

Related Questions