You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress 12.8.1无法操作Stripe Elements iframe问题及解决

Cypress 12.8.1 无法与 Stripe Elements 配合完成信用卡信息录入及支付创建的问题解决

我一直被该问题困扰许久,无法让Cypress 12.8.1与Stripe Elements配合完成信用卡信息录入及支付创建操作。查阅了大量资料,但所有方案均无效,恳请帮助。

尝试过的方案

  • 使用xpath方法,但未成功,对应报错信息及截图可参考相关issue评论。
  • 尝试使用第三方插件,但该插件已失效。
  • 尝试以下代码,但出现报错:
const $body = $element.contents().find('body')
let stripe = cy.wrap($body)
stripe.find('input[name="number"]').click().type('4242424242424242')
stripe = cy.wrap($body)
stripe.find('input[name="expiry"]').click().type('4242')
stripe = cy.wrap($body)
stripe.find('input[name="cvc"]').click().type('424')
})

对应报错截图可查看相关图片。

  • 尝试添加自定义Cypress命令"iframeLoaded",但无法适配Cypress 12的TypeScript格式,始终报错。

我在support/commands.ts中的代码如下:

// ***********************************************
// This example namespace declaration will help
// with Intellisense and code completion in your
// IDE or Text Editor.
// ***********************************************
declare namespace Cypress {
  interface Chainable<Subject = any> {
    iframeLoaded($iframe: any): typeof iframeLoaded;
  }
}

function iframeLoaded($iframe: any): Promise<any> {
  const contentWindow = $iframe.prop('contentWindow')
  return new Promise(resolve => {
    if (contentWindow && contentWindow.document.readyState === 'complete') {
      resolve(contentWindow)
    } else {
      $iframe.on('load', () => {
        resolve(contentWindow)
      })
    }
  })
}

Cypress.Commands.add('iframeLoaded', {prevSubject: 'element'}, iframeLoaded);

对应报错截图可查看相关图片。

问题解决(更新)

参考相关答案解决了问题,做出了三处修改,调整后的代码如下:

function getCardField(selector: any, attempts = 0) {
      Cypress.log({displayName: 'getCardField', message: `${selector}: ${attempts}`})
      
      if (attempts > 50) throw new Error('too many attempts')
    
      return cy.get('iframe', {timeout:10_000, log:false})
// CHANGE: .eq(1 to .eq(0
        .eq(0, {log:false})
        .its('0.contentDocument', {log:false})
        .find('body', {log:false})
        .then(body => {
          const cardField = body.find(selector)
          if (!cardField.length) {
            return cy.wait(300, {log:false})
              .then(() => {
                getCardField(selector, ++attempts)
              })
          } else {
            return cy.wrap(cardField)
          }
        })
    }
    
// CHANGE: "div.CardField" to "div.CardNumberField input"
    getCardField('div.CardNumberField input')
      .type('4242424242424242')

// CHANGE: "div.CardField" to "div.CardNumberField-input-wrapper"
getCardField('div.CardNumberField-input-wrapper')
    .find('input').eq(0)
    .should('have.value', '4242 4242 4242 4242')   // passes

内容的提问来源于stack exchange,提问作者MadMac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:04:56