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

Cypress如何获取元素htmlTemplate属性内的foo对应数值

Cypress 提取自定义属性中指定数值的实现方案

操作步骤

  • 第一步:通过选择器定位到目标<rect>元素
  • 第二步:调用invoke方法获取htmlTemplate属性的字符串值
  • 第三步:用正则匹配提取foo字段后的数字,按需转为数值类型

代码示例

基础版本(确认属性一定存在对应数值时使用):

// 可根据实际业务调整元素选择器
cy.get('rect.foo')
  // 获取htmlTemplate属性值
  .invoke('attr', 'htmlTemplate')
  .then(templateVal => {
    // 正则匹配foo: 后的数字,支持foo和数字之间有任意空格
    const targetNum = templateVal.match(/foo:\s*(\d+)/)[1]
    // 转为数字类型,可直接用于断言或后续逻辑
    const result = Number(targetNum)
    // 示例断言
    expect(result).to.eq(115)
  })

兼容异常场景版本:

cy.get('rect.foo')
  .invoke('attr', 'htmlTemplate')
  .then(templateVal => {
    const matchResult = templateVal.match(/foo:\s*(\d+)/)
    if (!matchResult || !matchResult[1]) {
      throw new Error('htmlTemplate属性中未匹配到foo对应的数值')
    }
    const result = Number(matchResult[1])
    // 后续业务逻辑
  })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:15:01