Handle Alerts in Cypress

 Alert : 

Display a message to the user with an OK button. The user must click OK to dismiss the alert


Here is the way to verify that the alert is clicked


cy.on('window:alert' ,  (str) => {
    expect(str).to.eq.('Text value')
})

Confirm Alert

Display a message to the user with the OK and Cancel buttons. The user can choose to confirm or cancel the action.


Here is the way to verify that the Cancel is clicked



cy.on('window:confirm', (text) => {

  expect(text).to.contains('Would you like to confirm?');

  return false;

});


Here is the way to verify that the Ok is clicked


cy.on('window:confirm', (text) => {

  expect(text).to.contains('Would you like to confirm?');

  return true;

});

Prompt Alert

In Prompt Alert user needs to enter text into the input field 


it('should trigger a prompt with a message', () => {

  cy.window().then(win => {

    cy.stub(win, 'prompt').returns('This is my answer.');

    cy.get('#prompt-button').click();

    cy.get('#prompt-answer').contains('Answer: This is my answer.');

  });

});

No comments:

Post a Comment