Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

    })

})
like image 593
soccerway Avatar asked Aug 11 '18 00:08

soccerway


People also ask

How do I get alert messages in Cypress?

Browser Automation with Cypress and Gherkin 2022 Cypress can work with alerts by default. The pop-up can be an alert or confirmation popup. Cypress is designed in such a way that it shall always click on the OK button on the pop-up. Moreover, Cypress has the ability to fire the browser events.

How do you verify text in Cypress?

Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element. cy.

How do you alert a string in JavaScript?

Alert Box. Use the alert() function to display a message to the user that requires their attention. This alert box will have the OK button to close the alert box. The alert() function takes a paramter of any type e.g., string, number, boolean etc.

How do you check for pop in Cypress?

It obtains the value of the object of the prompt (remote window). In a confirmation/alert pop-up, we have to fire a browser event. But for prompt pop-up, we have to use cy. stub() method.


2 Answers

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

    })

})
like image 99
soccerway Avatar answered Sep 24 '22 03:09

soccerway


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.

like image 32
codemon Avatar answered Sep 21 '22 03:09

codemon