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?
If you don't care about actually testing the dialog, you can add a listener at the top of the test.
function handler(win) {
const observer = new MutationObserver(mutations => {
const addedElement = mutations?[0].addedNodes?[0]
if (addedElement?.classList.contains('wps_popup')) {
addedElement.click()
}
}
observer.observe(win.document.body, { childList: true })
}
cy.on('window:load', handler)
This will run independently of the Cypress test, but please note it responds to each and every change to the DOM.
To minimize the impact on test runner, turn it off as soon as possible
it('tests with background handler', () => {
function handler(win) {
const observer = new MutationObserver(mutations => {
const addedElement = mutations?[0].addedNodes?[0]
if (addedElement?.classList.contains('wps_popup')) {
addedElement.click()
}
}
observer.observe(win.document.body, { childList: true })
}
cy.on('window:load', handler)
cy.visit('/')
// some test code
cy.off('window:load', handler) // turn off
})