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

Cypress中对比两个JSON文件的循环问题求助

Cypress中逐元素对比两个JSON文件的正确姿势

原代码问题分析

你的循环代码无法生效,核心有两个问题:

  • 循环内的断言没有使用循环变量i和j,始终对比固定索引[0][0],相当于重复做同一个断言,没有实现遍历
  • 内层循环的遍历逻辑错误,Object.keys(refEquityTable)是获取JSON对象的键名集合,而非data数组的长度,不符合遍历数组元素的需求

解决方案

方法1:使用Cypress内置Lodash遍历(推荐)

Cypress内置了Lodash库,用Cypress._.each处理遍历更稳妥,适配Cypress的异步执行逻辑:

cy.fixture('refEquityTable').then(refEquityTable => { 
  cy.fixture('equityTable').then(equityTable => {  
    // 遍历外层data数组的每一行
    Cypress._.each(refEquityTable.data, (refRow, rowIndex) => {
      const targetRow = equityTable.data[rowIndex];
      // 遍历当前行的每个元素
      Cypress._.each(refRow, (refValue, colIndex) => {
        expect(targetRow[colIndex]).to.equal(refValue);
      });
    });
  });
});

方法2:使用原生forEach循环

在then回调的同步上下文里,直接用原生数组forEach也可以,注意正确关联索引:

cy.fixture('refEquityTable').then(refEquityTable => { 
  cy.fixture('equityTable').then(equityTable => {  
    refEquityTable.data.forEach((refRow, rowIndex) => {
      const targetRow = equityTable.data[rowIndex];
      refRow.forEach((refValue, colIndex) => {
        expect(targetRow[colIndex]).to.equal(refValue);
      });
    });
  });
});

补充:仅对比单行元素(如data[0])

如果你的场景只需要对比data[0]这一行的所有元素,简化代码如下:

cy.fixture('refEquityTable').then(refEquityTable => { 
  cy.fixture('equityTable').then(equityTable => {  
    const refRow = refEquityTable.data[0];
    const targetRow = equityTable.data[0];
    
    refRow.forEach((refValue, index) => {
      // 可选添加失败提示,方便定位问题
      expect(targetRow[index]).to.equal(refValue, `元素[0][${index}]不匹配`);
    });
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:18:30