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

如何在Cypress中遍历表格提取所有行值并完成4个值的断言

问题分析与修复

你的代码存在两个问题导致无法获取第一个值:

  1. 代码里的if ($index!==0)条件主动跳过了索引为0的第一个单元格,直接排除了Value1;
  2. 断言语句有语法错误:.deep.eq.([...])多了一个多余的点,正确写法是.deep.eq([...])。

修改后的完整代码

let values = []
cy.visit(url)
cy.get('selector')
  .find('td')
  .each(($el, index) => {
    cy.wrap($el)
      .invoke('text')
      .then(text => {
        values.push(text.trim()) // 移除跳过索引0的判断
      })
  })
 .then(() => expect(values).to.deep.eq(["Value1", "Value2", "Value3", "Value4"]))

更简洁的写法(推荐)

可以利用Cypress的链式断言特性,避免手动维护数组,更符合异步处理逻辑:

cy.visit(url)
cy.get('selector')
  .find('td')
  .invoke('text')
  .then(text => text.split('\n').map(item => item.trim()).filter(Boolean))
  .should('deep.eq', ["Value1", "Value2", "Value3", "Value4"])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:30:41