0
0
CypressDebug / FixBeginner · 4 min read

How to Handle Popup in Cypress: Fix and Best Practices

In Cypress, you handle popups like alerts, confirms, or prompts by using 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.

javascript
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')
})
Output
Cypress test fails with error: "Uncaught alert blocked the test" or test hangs waiting for alert to close.
🔧

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.

javascript
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')
})
Output
Test passes with alert popup handled and result text verified.
🛡️

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:confirm and returning true or false.
  • Prompt popup not handled: Use cy.window() to stub window.prompt method.

Key Takeaways

Use cy.on('window:alert') and cy.on('window:confirm') to handle popups in Cypress tests.
Always set popup handlers before triggering actions that cause popups to avoid test failures.
Stub window methods like alert, confirm, and prompt to control popup behavior in tests.
Place popup handling code in beforeEach or custom commands for reuse and cleaner tests.
Ignoring popup handling causes tests to hang or fail with uncaught alert errors.