Reputation: 41
I have a question: What happens if I need to create a course of action based on an assert in Cypress? Suppose that when entering a certain page, there is a pop-up window that is visible randomly; sometimes it appears and sometimes it doesn't. So, I need to click the "OK" button on that popup when it appears just to make it go away. How can I make sure that the test does not fail on occasions when that window does not appear? The test fails since it does not find the corresponding element to the "Accept" button. How do I make it ignore that action when the window doesn't appear? Thank you in advance.
I tryed with something like this, but it doesn't work:
if(cy.get('#pop-up-window-1').should('exist')){
cy.get('#btn-accept').click()
}else{
nothing
}
Upvotes: 1
Views: 131
Reputation: 644
Using conditional testing can give you a flaky test.
If you test for the presence of the popup with if ($body.find('#pop-up-window-1').length)
the timing may be off, and sometimes it works and sometimes it does not.
That's particularly true if the modal uses animation to open.
One option is to wait for a suitable period before checking
cy.wait(3000)
cy.get('body').then($body => {
if ($body.find('#pop-up-window-1').length) {
cy.get('#btn-accept').click()
}
})
Upvotes: 0
Reputation: 18601
You can do something like this. Check the length and if its greater than 0, then element is present, if not then element is not present.
cy.get('body').then(($body) => {
if ($body.find('#pop-up-window-1').length > 0) {
//pop up is present
cy.get('#btn-accept').click()
} else {
cy.log('Pop Up not present. Moving on..')
}
})
Upvotes: 1