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
相关产品推荐
相关产品推荐

