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!')
})
})
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With