Dialog that appears conditionally during web page startup

Viewed 33

I need to handle the case where my page may display a popup dialog at the load stage, or it may not appear. Clicking anywhere will remove it and I'm not interested in testing this dialog, but it blocks the page I need to access so it must be removed

This is the code that will get the dialog when it appears

cy.get('.wps_popup')
  .find('[data-wps-popup-close]')
  .click()

but I cannot put that at the top of the test, because this element might not appear.

How do I handle a conditional element - do I need to intercept DOM changes and put that code in the event listener?

1 Answers

It is possible to poll for the element and continue if it does not occur during a certain timeout.

Note this will require a certain wait after page load, depending on how long the popup takes to appear.

The dialog will eventually not exist on the page, either it never arrived or because you ran your code to dismiss it.

cy.visit('/')
    
const getDialog = (selector, attempt = 0) => {
  if (attempt === 100) return null          // 10 seconds is up, no appearance

  cy.get('body', {log:false}).then(($body) => {
    const element = $body.find(selector)
    if (!element.length) {
      cy.wait(100, {log:false})             // wait in small chunks
      getDialog(selector, ++attempt)
    }
  })
  return cy.get(selector, {log:false})      // done, exit with the element
}

getDialog('.wps_popup')
  .then($el => {
    if($el && $el.length) {
      $el.find('[data-wps-popup-close]').click()
    }
  })
cy.get('div span').should('not.exist')

Related