Hire QA – Specialized in QA Recruitment, Technical Interviews and Testing Solutions

Cypress – How to Handle Alerts

Category: Cypress
//Click on Alert button to generate the alert
cy.get('.alert-button').click()
//Cypress will handle alerts using cy.on and window:alert
cy.on('window:alert', (t) => {
    expect(t).to.contains('This is JS Alert')
})
//Alert window automatically will be closed by Cypress

//Fetch the text from web page and validate
cy.get('.alert-message').should('have.text', 'You clicked on Alert')

//Handle JS Confirmation Alert. Confirmation alert will have OK and CANCEL button.
cy.get('.confirmation-alert-button').click()

//Cypress will handle alerts using cy.on and window:confirm
cy.on('window:confirm', (t) => {
    expect(t).to.contains('This is JS Confirmation Alert')
})
//Cypress automatically closes the alert by default clicking on OK button
cy.get('.alert-message').should('have.text', 'You clicked on OK')
//Click on CANCEL button on Confirm Alert
cy.on('window:confirm', ()=> false);


//Handle Javascript Prompt Alerts
//Get the control on prompt alert before generate the prompt alert

cy.window().then((win) => {
   cy.stub(win, 'prompt').returns('Welcome to JS Prompt Alert');
})
cy.get('prompt-alert-button').click();

//Authentication Prompt Alert
cy.visit("url", { auth: 
                                   {
                                     username : "admin",
                                     password  : "password"

                                     }
                         }
             );
or
cy.visit("https://username:password@url")

Leave a Reply

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