How to work on random pop ups in cypress?

2.2k Views Asked by At

I have an application, where feedback pop up comes in a page randomly; like pop up may or may not come in the page after loading it for nearly 3000ms. How to handle this pop up in cypress.

I tried below code:

        cy.get("div.QSIFeedbackButton").then(($body)=> {

        if($body.find('.QSIWebResponsiveDialog-Layout1-SI_0rEzRx2V9yqm1Yq_close-btn > img')){

          cy.get('.QSIWebResponsiveDialog-Layout1-SI_0rEzRx2V9yqm1Yq_content').contains('Help us improve our portal!')        
          cy.get('.QSIWebResponsiveDialog-Layout1-SI_0rEzRx2V9yqm1Yq_close-btn > img').click()
         } 

          else {
            cy.log('feed back pop up not found')
          }
        })

But this one always fails in IF block, when the pop up doesn't appear. I want to run the test gracefully, so that even if the pop up doesn't appear test should not fail & it should go to the else block. How can i do this in my test?

2

There are 2 best solutions below

0
On

If the popup disappears after some time, use this:

cy.get('random popup id').should('not.exist')

works great, because it checks if that popup exist in the DOM tree, even better if you can add testid to the popup

0
On

You can use 'MutationObserver' which is an event listener that gets triggered when a node is/nodes are added or removed from the DOM. You can then check whether the modal shows up (or simply the close modal button):

cy.document().then((document) => {
      new MutationObserver(function () {
        const closeModelBtn = Cypress.$('button');
        if (closeModelBtn.length) {
          closeModelBtn.trigger('click');
        }
      }).observe(document.body, { childList: true, subtree: true });
});

Note: this is asynchronous and independent from cypress (your cypress code is not gonna wait for this to execute so you might face some issue with the actions that are occurring at the same time as this).