Stubbing link inside an iframe

Viewed 51

I have an iframe containing an element with an href, when I click I want to stub the call and verify the url.

This is my code so far, not working. The error is "Timed out retrying after 8000ms: expected open to have been called at least once"

cy.window().then((win) => {
  cy.stub(win, 'open').as('open')
    .callsFake(url => {
      cy.wrap(url).as('href')
    });
})
cy.getIframeBody().find('#container a').click();
cy.get('@open').should('be.called');
cy.get('@href').should(url => {
  expect(url).to.eq('xyz')
});
1 Answers

The <iframe> has a different window to the one returned by cy.window().

You can obtain the iframe contentWindow first and place the stub on that.

cy.get('iframe')
  .its('0.contentWindow')
  .then(iframeWin => {

    cy.stub(iframeWin, 'open').as('open')
      .callsFake(url => {
        cy.wrap(url).as('href')
      });

    cy.getIframeBody().find('#container a').click();
    
    cy.get('@open').should('be.called');
    cy.get('@href').should(url => {
      expect(url).to.eq('xyz')
    })
  })
Related