2

I use Cypress to automate logging in to a web application, protected by an iFrame.

In my Selenium I can use a command to switch to iFrame:

driver.switchTo().frame(driver.findElement(By.xpath(".//*@id='app']/iframe")));

After that I can access iFrame elements as well.

But with Cypress, I don't know the method to switch to frame?

Chillie
  • 1,045
  • 10
  • 27
DuongDD
  • 21
  • 1
  • 2
  • 1
    Possible duplicate: [How do I enter data into a form input in an iframe using cypress?](https://stackoverflow.com/questions/47325258/how-do-i-enter-data-into-a-form-input-in-an-iframe-using-cypress?rq=1) – Joshua Wade Oct 09 '18 at 13:53
  • @JoshuaWade: thank you for your comment, I have found solution to resolve it. cy.get('iframe').then(function ($element) { const $body = $element.contents().find('body') const cyElement = cy.wrap($body) cyElement.find('[class=xxx]').click({force:true}) I hope this can help somebody save your time. – DuongDD Oct 11 '18 at 00:52

1 Answers1

0

In Cypress, you need to install a package called cypress-iframe in order to work on iFrame elements.

Run this command in your terminal to install:

npm install -D cypress-iframe

Import cypress-iframe package to your file:

import 'cypress-iframe';

To load an iFrame, use:

cy.frameLoaded("#id-of-an-iframe");

To find element inside iFrame, start with:

cy.iframe()

Here is the code example on how to use iFrame elements in Cypress:

/// <reference types="Cypress" />
/// <reference types="cypress-iframe" />
import 'cypress-iframe';

describe("Test Suite", () => {
    it("Test Case", () => {

        cy.visit("https://example.com");

        cy.frameLoaded("#iframe-id"); //Load iFrame

        cy.iframe().find("a[href*='services']").eq(0).click();  //click on link inside iFrame
        cy.iframe().find("h1[class*='service-title']").should("have.length", 2);  //assertion

    })
})
Force Bolt
  • 883
  • 7
  • 7