Cypress - iframe handling

Viewed 5834

I have some code that tries to catch elements inside an iframe but I just keep getting thrown back an error

it('Send Medication',function(){
       cy.get('.aut-iframe') 
       .should(iframe => expect(iframe.contents().find('body')).to.exist)
       .then(iframe => cy.wrap(iframe.contents().find('body')))
       .within({}, $iframe => {
            cy.get('.pending-medication-check-box').click({force:true})

This is the error that I get:

enter image description here

enter image description here

Lastly, this is the iframe info:

enter image description here

3 Answers

I would assume you are just missing retries for fetching the iframe until the body is loaded. Simple get and should combo doesn't wait for this to happen. Official docs state you should use .its('body') when working with iframes, so try something like this:

cy.get('.aut-iframe').its('body').then((body) => { cy.wrap(body).should('...') }

Reference: https://www.cypress.io/blog/2020/02/12/working-with-iframes-in-cypress/#header

First in your command file add this:

Cypress.Commands.add('getIframe', () => {
return cy
    .get('.aut-iframe')
    .its('0.contentDocument.body').should('not.be.empty')      
    .then(cy.wrap)
})

Then in your test you can use the command above in this way:

cy.getIframe()
  .get('.pending-medication-check-box').click({force:true})
  1. Install the cypress-iframe plugin.

  2. After installation write import 'cypress-iframe'; under cypress/support/commands.js

  3. Then finally your code should look like:

cy.frameLoaded('.aut-iframe')
cy.iframe('.aut-iframe')
  .find('.pending-medication-check-box')
  .should('be.visible')
  .click()
Related