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

如何在Cypress中将节点属性映射为数组

解决方法

可以通过两种简洁的方式实现需求:

方式一:转原生数组批量提取属性

cy.get('tr')
  .invoke('toArray') // 将Cypress元素集合转为原生DOM数组
  .then(trElements => {
    const result = trElements.map(tr => tr.getAttribute('specprop'))
    // 验证结果是否符合预期
    expect(result).to.deep.equal(['A', 'B'])
  })

方式二:遍历元素收集属性值

const specPropList = []
cy.get('tr')
  .each(tr => {
    specPropList.push(tr.getAttribute('specprop'))
  })
  .then(() => {
    expect(specPropList).to.deep.equal(['A', 'B'])
  })

关键说明

  • tr.getAttribute('specprop'):直接获取单个<tr>元素的specprop属性值
  • .invoke('toArray'):把Cypress包装的元素集合转成普通JS数组,方便用map这类原生数组方法批量处理
  • 最后用expect断言能确保生成的数组和预期完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:22:09