Cypress test never finishes when an unforeseen alert is triggered in the system during the test

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.

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.

Answer №1

To handle alerts on the <iframe> window in Cypress, you can use the cy.stub() method.

Additionally, an assertion has been included to verify that the stub received a call.

let stub;
cy.visit('http://127.0.0.1:5500/html/alert.html')

cy.get('iframe#myFrame')
  .its('0.contentWindow')
  .then(win => {
    stub = cy.stub(win, 'alert')
  })
  
cy.then(() => {
  // Ensure this code is inside a then callback since stub is set asynchronously
  cy.wrap(stub, {timeout:6_000}).should('have.been.called')
})

cy.title().should('eq', 'Button Alert Example')

cy.get('button').contains('Click me for a label').click();
cy.get('#label').should('have.text', 'You clicked the button!')

See the test log here:


Real-world Scenario with Iframes

In more complex applications, handling iframes may require additional steps beyond basic iframe code.

Using cypress-iframe can enhance the reliability of your tests when dealing with iframes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing appearance with $refs?

Having trouble adding style to the $refs attribute. I keep getting an error message saying "Cannot set property 'cssText' of undefined." Is there a way to accomplish this task? I haven't come across anything similar to this issue before. th ...

Storing Vue.js components as objects in a database: A step-by-step guide

Is there a way to serialize Vue.js components and store them in a database? For example, I am looking to save components like the HelloWorld component typically found in a fresh Vue installation. Any suggestions on a serialization process or package that ...

Unspecified data response error in Angular JS

As a beginner in Angular JS, I am currently working on calling a Rest API using JSON data. However, when I run the HTTP-server, I am not receiving my response data as expected. function retrieveContacts(contactsdata) { contactsdata.getContacts().the ...

What is the correct way to align an InputLabel in Material UI?

https://i.stack.imgur.com/Uafr1.png Looking for advice on styling the InputLabel in my code to improve its appearance. Code snippet below: <FormControl fullWidth> <InputLabel >Select EPE</InputLabel> <Select ...

How to retrieve document.getElementsByName from a separate webpage using PHP and javascript

Hey there, I've been searching for a solution to this issue but haven't had any luck so far. I'm attempting to retrieve the value of the name test from an external website. <input type="hidden" name="test" value="ThisIsAValue" /> Up ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

What is the best way to include arrays in VueJS?

Currently, I am working with two arrays in my Vue application. The first array called desserts lists all the desserts that I have. The second array, moreDesserts, displays checkboxes with values. When a user selects a checkbox, the value is added to the se ...

Hover state remains persistent even after modal window is activated in outouchend

One of the buttons on my website has a hover effect that changes its opacity. This button is used to share information on Facebook. It's a simple feature to implement. Here is the CSS code: .social_vk, .social_fb { height: 38px; obj ...

jQuery click() function fires twice when dealing with dynamic elements

I am loading content from a database through ajax into a div and then when clicking on any of these content pieces, it should reload new content. The ajax request is initialized as a method within a class that I call at the beginning: function Request(ta ...

Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database ...

Is it better to conceal modals or completely eliminate them from the DOM when working with React?

I am currently developing a React application that involves multiple modals, with only one active at a time and no nested modals. I am torn between two approaches for handling the showing and hiding of these modals: The first approach involves having a b ...

Guide to setting the radio_button checked for the first child element in Rails 4

Currently, I am working with rails4 and have encountered an issue related to a dropdown list. My goal is to automatically select the radio_button of the first child element when a parent item is chosen from the dropdown menu. Essentially, the dropdown cons ...

The chosen element contains a value of -1

When the select element has a selected value of 4, form data is sent to the server and the controller returns a partial view. <script> $(document).ready(function () { var objSel = document.getElementById("IDVacationApplicationTyp ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

Various gulp origins and destinations

I am attempting to create the following directory structure -- src |__ app |__ x.ts |__ test |__ y.ts -- build |__ app |__ js |__ test |__ js My goal is to have my generated js files inside buil ...

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...

User authentication in MEAN Stack using passport-local and $routeProvider for routing

When it comes to logging users into my application, I am utilizing passport-local. The login process involves a function called in my AngularJS controller: $http.post('/login', $scope.user).then(function (response){ if(response.data.success) ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

An error occurs even before any Components are rendered, with a TypeError stating that the property 'type' cannot be read because it is undefined

I'm facing an issue with my Redux App where the first component (App.js) is not rendering due to continuous errors. The reducer mentioned below is being triggered at some point without any action, causing the compiler to interpret action as null and f ...

Transferring data from client to server: Weighing the pros and cons of

When dealing with 1-5 variables on the client side that need to be sent to the server using AJAX (Post Method), there are two primary methods of getting them there. One option is to use JSON to encode and decode the variables, sending them as a JSON stri ...