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

Cypress+TS操作iframe报错:TypeError: data.its is not a function

Cypress+TypeScript访问iframe元素报错:TypeError: data.its is not a function

错误信息

TypeError
data.its is not a function

测试代码

getSAveCardElement()
  .click()
  .then(() => {
    getIFrame().xpath("//*[@name='cardnumber']").type(info.stripeCardNum);
  });

iframe处理函数代码

export const getIframeBody = () => {
  return cy.xpath("//div[@id='cardElementpaymentModal']//iframe[contains(@name,'privateStripeFrame')]").each((data) => {
    // @ts-ignore
    data.its('0.contentDocument').its('body').should('not.be.undefined').then(cy.wrap);
  });
};

问题分析

你用each循环获取iframe元素,但each回调里的data是jQuery/DOM元素,不是Cypress链式命令对象,而.its()是Cypress专属命令,只能在cy.xxx链式调用中使用,所以会抛出data.its is not a function的错误。

解决方案

去掉each循环,直接用.then()获取iframe的DOM元素,直接访问其contentDocument属性,再包装成Cypress对象即可。另外Stripe的iframe加载可能有延迟,建议添加等待确保body加载完成:

export const getIframeBody = () => {
  return cy.xpath("//div[@id='cardElementpaymentModal']//iframe[contains(@name,'privateStripeFrame')]")
    .then($iframe => {
      // 获取iframe的contentDocument
      const contentDocument = $iframe[0].contentDocument;
      // 等待body加载完成并包装成Cypress对象
      return cy.wrap(contentDocument.body).should('not.be.empty');
    });
};

使用修正后的函数

调用时需要在getIframeBody()之后用.within()来限定iframe内的元素查找范围:

getSAveCardElement()
  .click()
  .then(() => {
    getIframeBody().within(() => {
      cy.xpath("//*[@name='cardnumber']").type(info.stripeCardNum);
    });
  });

这样就能正确访问iframe内的元素,避免之前的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:31:04