October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Test Browser Alerts, Confirmations, and Prompts with Cypress

Cypress auto-accepts alerts and confirms by default; use event handlers for assertions and cancellation, and stub window.prompt before app code runs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cypress handles JavaScript window.alert(), window.confirm(), and window.prompt() differently: alerts are automatically accepted and can be observed with window:alert; confirms are automatically accepted unless a window:confirm handler returns false; prompts are best tested by stubbing window.prompt before application code runs. These tests exercise your app’s behavior, not the browser’s native dialog appearance.

How Cypress handles each browser dialog

Dialog Cypress default How to test it Can the test control the result?
window.alert() Automatically accepts it. Listen for window:alert and assert the message. No. The event lets you observe the alert; it does not provide an accept-or-reject choice.
window.confirm() Automatically accepts it. Listen for window:confirm. Yes. Return false from the handler to cancel; otherwise Cypress accepts it.
window.prompt() Use a stub for a controlled response. Stub window.prompt before app code runs. Yes. Return a string to model input, or null to model cancellation.

These are JavaScript window methods, not Cypress’s separate cy.prompt() command. Cypress documents its alert and confirmation event behavior in the Catalog of Events.

As an Amazon Associate I earn from qualifying purchases.

Test an alert message

Register the event handler before the click that triggers the alert. Cypress accepts the alert automatically, so the test can continue without manual interaction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
it('asserts the alert message', () => {
  const alertStub = cy.stub().as('alert')
  cy.on('window:alert', alertStub)

  cy.get('[data-cy="show-alert"]').click()
  cy.get('@alert').should('have.been.calledWith', 'Saved successfully')
})

The assertion verifies the string passed to window.alert(). It does not verify how a native browser dialog looks or whether a user can interact with its visual rendering.

Test both confirmation outcomes

Accept the confirmation

With no cancellation handler, Cypress automatically accepts the confirmation. Trigger the action and assert the accepted result in the application, such as the item disappearing after a successful deletion.

it('deletes an item after confirmation', () => {
  cy.get('[data-cy="delete"]').click()
  cy.get('[data-cy="item"]').should('not.exist')
})

Cancel the confirmation

Return false from the event handler to exercise the cancelled branch. Assert both the message and the resulting application state.

it('keeps an item when deletion is cancelled', () => {
  cy.on('window:confirm', (message) => {
    expect(message).to.equal('Delete this item?')
    return false
  })

  cy.get('[data-cy="delete"]').click()
  cy.get('[data-cy="item"]').should('exist')
})

A handler that returns nothing does not cancel the confirmation. Cypress’s event documentation describes returning false as the cancellation mechanism.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test prompt input and cancellation

Install the stub before application code

For an end-to-end test, use cy.visit()’s onBeforeLoad callback to replace window.prompt before the page’s app code executes. The stub returns the value the app should receive.

it('uses the entered prompt value', () => {
  cy.visit('/', {
    onBeforeLoad(win) {
      cy.stub(win, 'prompt').as('prompt').returns('Ada Lovelace')
    },
  })

  cy.get('[data-cy="set-name"]').click()
  cy.get('[data-cy="greeting"]').should('have.text', 'Hello, Ada Lovelace!')
  cy.get('@prompt').should('have.been.calledWith', 'Enter your name:')
})

This checks both the prompt’s argument and the user-visible result produced from the returned string.

Model prompt cancellation

Return null to represent a cancelled prompt. Then assert the app’s intended cancellation behavior; for example, that it leaves the name unchanged or displays no greeting.

it('does not set a name when the prompt is cancelled', () => {
  cy.visit('/', {
    onBeforeLoad(win) {
      cy.stub(win, 'prompt').as('prompt').returns(null)
    },
  })

  cy.get('[data-cy="set-name"]').click()
  cy.get('[data-cy="greeting"]').should('not.contain', 'Hello,')
  cy.get('@prompt').should('have.been.calledWith', 'Enter your name:')
})

Adjust the final assertion to match the app’s actual cancellation contract. For component tests, stub the browser method before mounting the component; onBeforeLoad is the end-to-end page-load technique.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Listener timing, aliases, and stub lifecycle

  • Attach cy.on('window:alert', ...) or cy.on('window:confirm', ...) before the action that opens the dialog, or the event may already have fired.
  • Use .as() on a stub when you want to assert it later with cy.get('@name').
  • Cypress documents that listeners attached with cy.on() are removed at the end of the test. A per-test listener avoids leaking behavior into later tests.
  • Cypress stubs are restored between tests. The cy.stub() documentation covers stubbing and restoration; the bundled Sinon-Chai assertions support assertions such as calledWith.

Keep beforeunload tests separate

A page’s beforeunload event is not the same as window.prompt(). Do not use the prompt-stub pattern to test navigation warnings. Cypress’s migration guide demonstrates listening to window:before:unload and checking event.returnValue.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot failed dialog tests

  • The alert assertion never runs: Register the window:alert listener before clicking the trigger, and confirm that the app calls window.alert() in that test path.
  • A confirmation always takes the accepted branch: Return false from the window:confirm handler to cancel. An assertion alone does not cancel it.
  • The prompt returns the real dialog result or does not use the stub: Install the stub in onBeforeLoad for an end-to-end visit, before app code starts. If application code captures or calls the original method earlier, a later replacement may be too late.
  • A prompt cancellation test behaves like empty input: Return null for cancellation, not an empty string. The app may deliberately treat those values differently.
  • A test passes on the message but misses a bug: Also assert the UI or application state that should result from acceptance, cancellation, or entered prompt text.

Or skip the browser setup

ScreenshotNeo is a website screenshot API, not a Cypress dialog-testing replacement. For a website screenshot, one GET request returns an image; see the ScreenshotNeo site and API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each step can be turned off.
  • Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Responses identify the page verdict and billing status in headers.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000.

Sign up for 1,000 free screenshots a month, with no card required.

Coverage checklist

  • Assert the alert message and remember that Cypress auto-accepts it.
  • Exercise both accepted and cancelled confirmation paths.
  • Test prompt input and cancellation with a string and null.
  • Check the app’s resulting UI or state, not only the dialog call.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.