【问题标题】:How switch to iFrame with Cypress如何使用 Cypress 切换到 iFrame
【发布时间】:2018-10-09 12:15:55
【问题描述】:

我使用 Cypress 自动登录到受 iFrame 保护的 Web 应用程序。

在我的 Selenium 中,我可以使用命令切换到 iFrame:

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

之后我也可以访问 iFrame 元素。

但是用Cypress,不知道怎么切换到frame?

【问题讨论】:

  • @JoshuaWade:感谢您的评论,我已经找到解决方案。 cy.get('iframe').then(function ($element) { const $body = $element.contents().find('body') const cyElement = cy.wrap($body) cyElement.find('[ class=xxx]').click({force:true}) 我希望这可以帮助别人节省你的时间。

标签: cypress


【解决方案1】:

在 Cypress 中,您需要安装一个名为 cypress-iframe 的软件包才能处理 iFrame 元素。

在终端运行此命令进行安装:

npm install -D cypress-iframe

cypress-iframe 包导入到您的文件中:

import 'cypress-iframe';

要加载 iFrame,请使用:

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

要在 iFrame 中查找元素,请从:

cy.iframe()

下面是如何在 Cypress 中使用 iFrame 元素的代码示例:

/// <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

    })
})

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2021-11-14
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2020-11-23
    • 2021-06-19
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多