How to test an Alert with Cypress

Viewed 112

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?

2 Answers

The code cy.on('window:alert') is an event listener.

Instead of adding a callback as you would do for other commands, you can add a stub and check the stub function has been called plus the text it is called with.

Also because it's a listener, you must set it up before the event that triggers the event.

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

  it('Assert that the alert is displayed after entering data', () => {
    cy.visit('/')     

    const stub = cy.stub()
    cy.on ('window:alert', stub)

    cy.get('input').type('some data').blur()

    // wait for the event to be handled
    cy.then(() => {                       
      expect(stub.getCall(0)).to.be.calledWith('alert text')
    })

  })
})

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()
  })
})
Related