How to accept a window confirm fired by an iframe with Cypress

Viewed 492

I'm having some problems with Cypress when I need to accept a window confirm popup that is fired from a iframe. Cypress it's not very friendly with iframes, but I managed to make it work until I've found that need.

So here's what I've tried (based on this):

cy.get("[title='Some title']").then(($iframe) => {
      const $body = $iframe.contents().find("body");
      const $win = $iframe[0].contentWindow;

      cy.stub($win, "confirm").as("windowConfirm");

      cy.wrap($body)
        .contains("Delete") 
        .click() // this fires the confirm popup
        .should(function () {
          expect(this.windowConfirm).to.be.calledWith(
            `Continue deletion?`
          );
        });
    });

It actually asserts the text inside the popup, but never accepts it. I've tried different methods I've found (i.e. using a.on("window:confirm", () => true) but I've got no results.

Thank you!

1 Answers

Just add your truthy function to the stub

cy.stub($win, 'confirm', () => true)
  .as('windowConfirm')

Prints CONFIRMED to the console.


it('confirms in iframe', () => {

  cy.visit('../app/iframe-confirm-popup.html')

  cy.get('iframe').then(($iframe) => {
    const $body = $iframe.contents().find('body')
    const $win = $iframe[0].contentWindow

    cy.stub($win, 'confirm', () => true)
      .as('windowConfirm')
    cy.stub($win.console, 'log').as('consoleLog')

    cy.wrap($body)
      .find('input').click().should(function () {
        expect(this.windowConfirm).to.be.calledWith('Are you sure you want to submit your application?')
        expect(this.consoleLog).to.be.calledWith('CONFIRMED')  // passes
      })
  })
})
Related