0

How do I take an iframe if I have two with the same classes and neither eq() nor first() works when I use cy.iframe().

Here is the error:

Each radio is made up of a 'form' and inside each one contains the respective iframe.
But I only want to take the one that is checked

enter image description here*

This is my script

enter image description here

Fody
  • 23,754
  • 3
  • 20
  • 37
Roly
  • 25
  • 4

2 Answers2

0

I'm guessing you're using cypress-iframe since cypress doesn't have a built-in iframe command available.

As you can tell, iframe() allows passing a selector. If your iframe tags are identical in their attributes so you cannot use attributes to select, or you just want to use the order, note that you have to use that as part of the selector. Instead use a selector that has the order part of it such as :first or :nth-child(n)

// will NOT work
cy.iframe().first()
cy.iframe().eq(1)

// will work
cy.iframe("iframe:first")
// for 2nd item use 2, since it uses a 1 based index
cy.iframe("iframe:nth-child(2)")
Daniel
  • 34,125
  • 17
  • 102
  • 150
  • Here `("iframe:nth-child(2)")` I tried with (0),(1),(2) trying to get one and it doesn't work the same error appears and in the case of `("iframe:first")` neither the error remains. Any recommendation – Roly Nov 01 '22 at 19:01
  • I've tested this in a setup with two `iframe`s using cypress v10.8.0 and cypress-iframe v1.0.1 so I'm certain it should work. Is it possible that the iframes haven't loaded yet? – Daniel Nov 01 '22 at 20:20
0

I can't see why cy.iframe('iframe:first') would not work, but if you have independent parent elements, e.g the <form> element mentioned, it's possible to pre-select the correct parent and apply cy.iframe() using that parent as "root" element.

The .within() command changes the root element:

cy.visit('/', {
  onBeforeLoad(win) {
    cy.stub(win.console, 'log').as('consoleLog')if you 
  }
})
cy.get('@consoleLog').should('be.calledWith', 'Iframe Loaded')

cy.get('iframe').eq(0)
  .parent()
  .within($iframeParentElement => {
    cy.iframe()
      .should('have.length', 1)   // expected <body> to have a length of 1  ✅
      .find('input#data')
      .should('have.length', 1)   // expected <input#data> to have a length of 1 ✅
  })

I also added a check on the "IFrame Loaded" console message that Tokenex emits, so as to delay <iframe> commands until loading is complete.

Fody
  • 23,754
  • 3
  • 20
  • 37