As soon as we visit website these days we will be promoted with popups and alerts. These alerts are sometimes might be the exciting deals you were waiting for or might be an important alert on privacy policy updated on your favorite site.
What if you have a requirement to handle these alerts!, Is it even possible to handle them on Cypress?! If you are wondering with these questions then the answers is yes. Cypress do support handling Alerts.
It will automatically handle both popups as well as the alert when they appear on the screen. In this post we will show you exactly how to handle them.
CODE
/// <reference types = "Cypress" />
describe('Handling Popups',function(){
context('Test Cases',function(){
it('Test 01',function(){
cy.visit('http://the-internet.herokuapp.com/javascript_alerts')
cy.get(':nth-child(1) > button').click()
cy.on('window:alert', (str) =>
{
expect(str).to.equal('I am a JS Alert')
})
cy.get(':nth-child(2) > button').click()
cy.on('window:confirm', (str) =>
{
expect(str).to.equal('I am a JS Confirm')
})
})
})
})
EXPLANATION
We first visit the site http://the-internet.herokuapp.com/javascript_alerts to test our popups.
When the Alert button is pressed the cypress test runner automatically mark it as true so you won't be able to view in UI, but it can be view in the log of the Cypress Test runner.
The same goes for the confirm popups.
Download the spec file below,
https://drive.google.com/file/d/1YmZIE1JDQ4DHJXDOSF43f2-Gv0fJFKVg/view?usp=sharing