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.
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();
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With