【问题标题】:Cypress - run test in iframe赛普拉斯 - 在 iframe 中运行测试
【发布时间】:2019-12-27 13:22:27
【问题描述】:

我正在尝试在 iframe 中查找元素,但它不起作用。

有没有人有一些系统可以在 iframe 中使用 Cypress 运行测试?一些进入 iframe 并在那里工作的方法。

【问题讨论】:

    标签: automation automated-tests cypress


    【解决方案1】:

    这适用于我在本地和通过 CI。图片来源:Gleb Bahmutov iframes blog post

     export const getIframeBody = (locator) => {
      // get the iframe > document > body
      // and retry until the body element is not empty
      return cy
        .get(locator)
        .its('0.contentDocument.body').should('not.be.empty')
        // wraps "body" DOM element to allow
        // chaining more Cypress commands, like ".find(...)"
        // https://on.cypress.io/wrap
        .then(cy.wrap)
    }
    

    spec file:

        let iframeStripe = 'iframe[name="stripe_checkout_app"]'
      getIframeBody(iframeStripe).find('button[type="submit"] .Button-content > span').should('have.text', `Buy me`)
    

    【讨论】:

      【解决方案2】:

      这是here 提到的一个已知问题。您可以创建自己的自定义 cypress 命令来模拟 iframe 功能。将以下功能添加到您的cypress/support/commands.js

      Cypress.Commands.add('iframe', { prevSubject: 'element' }, ($iframe, selector) => {
        Cypress.log({
          name: 'iframe',
          consoleProps() {
            return {
              iframe: $iframe,
            };
          },
        });
        return new Cypress.Promise(resolve => {
          resolve($iframe.contents().find(selector));
        });
      });
      

      那么你可以这样使用它:

      cy.get('#iframe-id')
        .iframe('body #elementToFind')
        .should('exist')
      

      此外,由于 CORS/同源策略的原因,您可能必须在 cypress.json 中将 chromeWebSecurity 设置为 false(将 chromeWebSecurity 设置为 false 允许您访问嵌入在应用程序中的跨域 iframe并且还可以导航到没有跨域错误的任何超级域。

      这是一种解决方法,它在本地对我有用,但在 CI 运行期间不起作用。

      【讨论】:

      • 您找到在 CI 中运行测试的方法了吗?
      • @SupratikRulz 是的,看看我的回答,在 github 操作上可以正常工作
      【解决方案3】:

      这是正确的。赛普拉斯不支持 iframe。这很简单,目前不可能。您可以关注(并投票)这张票:https://github.com/cypress-io/cypress/issues/136

      【讨论】:

        猜你喜欢
        • 2021-11-06
        • 2023-02-10
        • 2019-07-29
        • 2022-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-14
        • 1970-01-01
        相关资源
        最近更新 更多