如何在Cypress中获取Stripe Element 解决Stripe iframe内卡号输入问题
Ionic + Stripe Payments 端到端测试卡号输入问题解决思路
Ionic封装的stripe-payments组件默认采用Shadow DOM隔离内部DOM结构,且加载逻辑和原生Stripe Elements有差异,通用的Stripe测试方案无法直接适配,可按以下步骤排查解决:
- 先调整Cypress基础配置,在
cypress.config.js中新增两个配置项:
关闭Chrome跨域安全限制,允许Cypress操作跨域的Stripe iframe内容。module.exports = defineConfig({ e2e: { chromeWebSecurity: false, experimentalSessionAndOrigin: true } }) - 自定义适配Ionic结构的Stripe元素获取命令,要先穿透Shadow DOM再查找iframe:
Cypress.Commands.add('getStripeInput', (inputName) => { // 先定位Ionic的stripe-payments组件 return cy.get('stripe-payments') // 穿透组件的Shadow DOM .shadow() // 匹配Stripe生成的iframe .find('iframe[name^="__privateStripeFrame"]') .its('0.contentDocument.body') .should('not.be.empty') .then(cy.wrap) // 查找对应输入框,支持cardnumber、expiry、cvc等 .find(`input[name="${inputName}"]`) }) - 输入测试内容时避开Stripe的安全校验,不要强制赋值,用原生type方法逐位输入,可加延迟模拟真实操作:
// 输入测试卡号 cy.getStripeInput('cardnumber').type('4242424242424242', { delay: 10 }) // 输入有效期 cy.getStripeInput('expiry').type('1230', { delay: 10 }) // 输入CVC cy.getStripeInput('cvc').type('123', { delay: 10 }) - 如果偶现输入失败,可在调用
getStripeInput前加1s等待,适配Ionic组件懒加载导致的iframe渲染延迟。
内容的提问来源于stack exchange,提问作者Алексей Горбунов
相关产品推荐
相关产品推荐

