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

soccerway picture soccerway · Aug 11, 2018 · Viewed 10.3k times · Source

How can we test the alert and text inside is displaying using Cypress.io Js automation framework? I am unable to figure out the relevant example in Cypress documentation, please advise.

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')     
    cy.get('button').contains('Click me!').click()
    cy.on ('window:alert', 'I am an alert box!')    

    })

})

Answer

soccerway picture soccerway · Aug 11, 2018

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!')      
    })  

    })

})