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

