How can we test the alert and text inside is displaying using Cypress.io Js automation framework?

Figured out the answer using cy.stub() method as advised by Richard Matsen:

describe('Test an alert and the text displaying', function() {
it('Verify alert and its text content', function(){
    cy.visit('http://www.seleniumeasy.com/test/javascript-alert-box-demo.html')    

    const stub = cy.stub()  
    cy.on ('window:alert', stub)
    cy
    .get('button').contains('Click me!').click()
    .then(() => {
      expect(stub.getCall(0)).to.be.calledWith('I am an alert box!')      
    })  

    })

})

This is a much simpler and more intuitive way:

cy.on('window:alert', (str) => {
  expect(str).to.equal(`This is an alert box!`)
})

I've found the stub() method of doing this to be way too messy, unintuitive and error-prone.


I couldn't get the accepted answer using .stub() to work, despite it being official Cypress solution for alert. Apparently I'm not alone here so I thought I'd share my workaround in case it helps someone in the same boat.

Expanding on @codemon's answer, this workaround will fail the test if no alert was fired:

   var alerted = false;
   cy.on('window:alert', msg => alerted = msg);

   cy.get('button').contains('Click me!').click() //or whatever code that triggers alert
   .then( () => expect(alerted).to.match(/clicked!/); //or whatever regex is appropriate