Alerts and popup in cypress:
Cypress can work with alert 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 browser events.
An alert is triggered by window:alert event. This is by default handled by Cypress and the OK button on the alert gets clicked, without being visible during execution.
There are 3 types of alerts:
- Simple alerts with alert text, Ok button
- Confirm alerts with alert text, Ok & Cancel button
- Prompt alerts with alert text box, Ok & Cancel button
1. Simple alerts with alert text, Ok button
When the alert occurs window:alert is the browser event that is triggered by default for the alert event. Cypress automatically handles the event by clicking the OK button.
2. Confirm alerts and popup with alert text, Ok & Cancel button
When a confirmation alert message occurs window:confirm is the browser event that is triggered. In addition, the confirmation popup by default cypress clicks the OK button. But we can also click the cancel button in the confirmation popup by returning false in the events.
3. Prompt alerts with alert text box, Ok & Cancel button
Prompt is used to get value from the user in text format. It provides a text bar for user input; Prompt is a rarely used alert type.
- cy.window() command fetches the object value of the currently active window.
- In the below program since manual promises are resolved, cy.window() fetches the object value of the remote window which is the prompt window.
- Like the alert and confirmation, there is no event named “window: prompt”. So to handle the prompt cy.stub() is used.
- cy.stub() is used when we know what object will be exactly returned. Instead of calling the original function or method cy.stub() is replaced with the original function.