When a web application unexpectedly throws an error using an alert box, the Cypress test becomes stuck indefinitely. The test will not complete or fail until the user manually closes the browser or clicks on the OK button within the alert box.
https://i.sstatic.net/ce9xy.png
I have created a sample HTML page below to demonstrate this issue. In this example, I intentionally trigger an alert box after 5 seconds of the page loading.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Button Alert Example</title>
</head>
<body>
<button onclick="changeLabel()">Click me for a label</button>
<p id="label"></p>
<iframe id="myFrame" style="display:none;"></iframe>
<script>
// Show alert after 5 seconds of page load within the frame
setTimeout(function() {
var frame = document.getElementById('myFrame');
frame.style.display = 'block';
frame.contentWindow.alert("Error While Processing Request");
}, 5000);
function changeLabel() {
document.getElementById('label').innerText = "You clicked the button!";
}
</script>
</body>
</html>
The following Cypress test can replicate the issue:
describe('Reproduce Alert Test', () => {
it('Handle alert in a Frame', () => {
cy.visit('/alert-test.html');
cy.wait(6000)
// Verify page title
cy.title().should('eq', 'Alert Example');
// Click the button and verify the label
cy.get('button').contains('Click me for a label').click();
cy.get('#label').should('have.text', 'You clicked the button!');
});
});
NOTE: This issue occurs when an iFrame is present on the webpage. Without an iFrame, Cypress automatically accepts the alert message.