【问题标题】:cannot locate 'iframe' using cypress无法使用 cypress 找到“iframe”
【发布时间】:2021-02-03 11:38:49
【问题描述】:

我正在使用 cypress 来测试我的网站,我想要实现以下目标: 在此链接下:https://www.glassboxdigital.shop/product-page/classic 当我点击“添加到购物车”时

有一个从右侧弹出的侧面板:

我想点击“查看购物车”按钮,我的第一次尝试是天真的 - 获取元素定位器并点击它,因为我看到它失败了,我调查了一下,发现它是“iframe”我尝试使用“iframe”,指出如下:

cy.get("iframe[frameborder='0']:nth-child(2)").then(function($elem){
     var ifele = $elem.contents().find("a[id*='view-cart-button']")
     cy.wrap(ifele).click()

但是当我运行它时,结果是:

Expected to find element: undefined, but never found it

cy.get("iframe[frameborder='0']:nth-child(2)").then(function($elem){
  16 |             var ifele = $elem.contents().find("a[id*='view-cart-button']")
> 17 |             cy.wrap(ifele).click()
     |                ^
  18 |         })
  19 |     
  20 |     }

【问题讨论】:

    标签: selenium iframe cypress ui-testing


    【解决方案1】:

    它无法定位元素,因为在调用侧边栏时将侧面板生成到 html 中,但赛普拉斯在调用侧边栏之前正在页面上搜索元素。

    编辑代码以执行构成侧栏的任何脚本,然后使用您之前尝试过的元素位置。

    【讨论】:

    • 我不太明白你的解决方案
    • 元素定位器在 HTML 文件中定位对象,但您的 HTML 文件发生了变化。当侧边栏显示和隐藏时,HTML 看起来不同。您可能正试图在侧栏的 HTML 实际存在之前获取它。
    【解决方案2】:

    由于 cypress 不提供处理 iframe 的本地方式,因此我们将创建一个自定义命令,基本上是遍历 iframe。去cypress/support/command.js写:

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

    您的测试应如下所示:

    it('Go inside iframe and click', function() {
      
        //Visit webpage
        cy.visit("https://www.glassboxdigital.shop/product-page/classic")
      
        //Wait till the Let's Chat header is visible
        cy.get('#comp-jor13ajz > .yuKeh').should('be.visible')
      
        //Click on the Add to Cart button
        cy.get('[data-hook="add-to-cart"]').click()
      
        //Go inside iframe and click View cart button
        cy.getIframe('iframe[name*="tpapopup"]').contains('View Cart').click({
            force: true
        })
    })
    

    执行后:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多