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

Cypress如何通过不含undefined的部分元素名称查找目标元素

实现方案

你可以通过Cypress的元素过滤功能,仅使用line-chart这段不含undefined的字符匹配目标元素,常用实现方式如下:

  • 方法1:前缀匹配过滤
    该写法兼容性最高,可自定义匹配规则
cy.get('*').filter((index, element) => {
  // 统一转小写避免大小写匹配误差
  const tagName = element.tagName.toLowerCase()
  // 仅匹配标签名以line-chart开头的元素
  return tagName.startsWith('line-chart')
})

如果需要严格排除标签名含undefined的元素,只要把返回逻辑改为:

return tagName.startsWith('line-chart') && !tagName.includes('undefined')
  • 方法2:正则匹配
    写法更简洁,适合明确标签规则的场景
// 直接匹配标签名含line-chart前缀的元素
cy.get(/^line-chart/)

针对你给出的<line-chart-undefined tabindex="0"></line-chart-undefined>HTML样例,以上两种写法都可以成功定位到目标元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:45:04