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

使用Cypress验证页面两个表格间的数值计算正确性

Cypress 表格计算逻辑校验方案

针对你需要验证的公式 表格1数值 = 表格2数值 + 表格2差值,可以通过以下步骤实现联合校验:

步骤1:提取表格数据并结构化

先分别获取两个表格的内容,转换为便于对比的键值对结构,以行标识(A/B/C)作为关联依据:

// 获取Current表格的数值映射
cy.get('table:first tbody tr').then(rows => {
  const currentValues = {};
  rows.each((index, row) => {
    const key = Cypress.$(row).find('td:first').text().trim();
    const value = Number(Cypress.$(row).find('td:last').text().trim());
    currentValues[key] = value;
  });

  // 获取Future表格的数值与差值映射
  cy.get('table:last tbody tr').then(futureRows => {
    const futureData = {};
    futureRows.each((index, row) => {
      const key = Cypress.$(row).find('td:first').text().trim();
      const value = Number(Cypress.$(row).find('td:nth(1)').text().trim());
      // 自动处理差值的正负号,转换为数字
      const diff = Number(Cypress.$(row).find('td:last').text().trim());
      futureData[key] = { value, diff };
    });

    // 步骤2:按行校验计算逻辑
    Object.keys(currentValues).forEach(key => {
      const currentVal = currentValues[key];
      const { value: futureVal, diff: futureDiff } = futureData[key];
      expect(currentVal).to.eq(futureVal + futureDiff, `行${key}计算逻辑不匹配`);
    });
  });
});

代码说明

  • 用table:first和table:last定位两个表格,实际测试中建议给表格添加专属class(如class="current-table"),让选择器更稳定
  • 通过.each()遍历表格行,提取每行的标识(A/B/C)和对应数值
  • 差值文本(如+10、-70)可直接用Number()转换为数字,自动识别正负号
  • 断言时添加自定义错误信息,方便快速定位校验失败的行

简化版实现(行顺序固定时)

如果两个表格的行顺序完全对应,可直接按索引遍历对比,无需提取键值对:

cy.get('table:first tbody tr').then(currentRows => {
  cy.get('table:last tbody tr').each((futureRow, index) => {
    const currentVal = Number(Cypress.$(currentRows[index]).find('td:last').text().trim());
    const futureVal = Number(Cypress.$(futureRow).find('td:nth(1)').text().trim());
    const futureDiff = Number(Cypress.$(futureRow).find('td:last').text().trim());
    expect(currentVal).to.eq(futureVal + futureDiff);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:05:22