How to Handle Popup in Cypress: Fix and Best Practices
cy.on('window:alert'), cy.on('window:confirm'), or cy.window() to stub or control them. This lets you test popup behavior without real browser dialogs blocking your tests.Why This Happens
Popups such as alerts or confirms block the browser and stop Cypress tests if not handled properly. Cypress does not automatically accept or dismiss these popups, so tests fail or hang waiting for user interaction.
it('fails when alert popup appears', () => { cy.visit('https://example.com') cy.get('#show-alert').click() // triggers alert popup cy.get('#result').should('contain', 'Alert handled') })
The Fix
Use cy.on('window:alert') to listen for alert popups and automatically handle them. For confirm popups, use cy.on('window:confirm') to control the response (accept or cancel). This prevents tests from hanging and lets you assert popup text.
it('handles alert popup correctly', () => { cy.visit('https://example.com') cy.on('window:alert', (text) => { expect(text).to.equal('This is an alert') }) cy.get('#show-alert').click() cy.get('#result').should('contain', 'Alert handled') })
Prevention
Always add event listeners for popups in your tests before triggering actions that cause them. Use cy.on('window:alert') and cy.on('window:confirm') to stub or verify popup messages. Avoid real browser dialogs by stubbing window methods if possible.
Keep popup handling code reusable by placing it in beforeEach hooks or custom commands.
Related Errors
Common related errors include:
- Uncaught alert blocked the test: Happens when alert is not handled.
- Confirm popup blocks test: Fix by stubbing
window:confirmand returningtrueorfalse. - Prompt popup not handled: Use
cy.window()to stubwindow.promptmethod.