cypressalert

How to test an Alert with Cypress


I'm testing a data form using Cypress, but am stuck on a step that displays an alert on the page.

This is the test, but it's not working.

describe('Alert is displayed with warning text', () => {

  it('Assert that the alert is displayed after entering data', () => {
    cy.visit('/')     
    cy.get('input').type('some data').blur()
    cy.on ('window:alert', (text) => {
      cy.wrap(text).should('eq', 'alert text')
    })    
  })
})

How do I test this alert that pops up on the page?


Solution

  • You can modify your code to use expect() instead of should().

    The problem is Cypress does not like commands inside event listeners.

    You must use a done() callback to avoid a false positive when the alert is not fired.

    describe('Alert is displayed with warning text', () => {
    
      it('Assert that the alert is displayed after entering data', (done) => {
        cy.visit('/')     
    
        cy.on('window:alert', (text) => {
          expect(text).to.eq('alert text')
          done()                              // waiting for event, fails on timeout    
        })
    
        cy.get('input').type('some data').blur()
      })
    })