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

使用Cypress访问PrimeNG表格时触发Cannot read properties of undefined(reading 'rows')错误

解决PrimeNG表格测试中「Cannot read properties of undefined (reading 'rows')」错误

我们在使用PrimeNG表格,编写了一个函数用于检查表格中是否存在特定文本元素,但运行代码时触发了「Cannot read properties of undefined (reading 'rows')」错误,错误出现在table.rows()调用处。另外,switch语句仍处于开发阶段,相关代码如下:

verifyTemplatePresent(template: string, table: any) {
    cy.get(this.#templateDataTable, {timeout: 30000}).within(() => {
        table.rows((element: any) => {
            const cellText = element.find('td').eq(0).text();
            switch (cellText === template) {
                case true:
                    return cy.get(this.fieldTd(element))
                        .should('exist');
                case false:
                    return cy.get(this.fieldTd(element))
                        .should('not.exist');
                default:
                    throw new Error("A wrong text was entered in the table, please change it to a correct value");
            }
        });
    })
}

解决思路

  • 检查table参数传入有效性
    错误核心是table变量为undefined,说明调用verifyTemplatePresent时没有传入有效的PrimeNG表格实例,或者传入的值为空。排查调用该函数的代码,确认传入的table参数是否是正确获取到的p-table组件对象(比如通过@ViewChild获取的实例)。

  • 改用Cypress原生遍历逻辑
    在Cypress的测试代码中,依赖外部传入的表格实例容易出现上下文问题,直接用Cypress选择器定位表格行更稳定。可以修改代码,直接遍历表格内的行元素:

    verifyTemplatePresent(template: string) {
      cy.get(this.#templateDataTable, {timeout: 30000}).within(() => {
        // 先确保表格已加载出行数据
        cy.get('tr').should('have.length.greaterThan', 0);
        
        cy.get('tr').each(($row) => {
          const cellText = $row.find('td').eq(0).text().trim();
          if (cellText === template) {
            // 找到匹配行后断言目标元素存在
            cy.wrap($row).find(this.fieldTd($row)).should('exist');
          }
        }).then(($rows) => {
          // 遍历结束后检查是否找到匹配项,未找到则抛出错误
          const matched = $rows.toArray().some(row => {
            return Cypress.$(row).find('td').eq(0).text().trim() === template;
          });
          if (!matched) {
            throw new Error(`表格中未找到指定文本:${template}`);
          }
        });
      });
    }
    
  • 修正断言逻辑
    原代码中每一行都会触发断言,这会导致不匹配的行直接断言失败,不符合“检查特定文本是否存在”的需求。正确逻辑应该是:找到匹配文本的行后断言目标元素存在;若遍历完所有行都未找到匹配项,再抛出错误或断言失败。

  • 确保表格数据完全渲染
    虽然设置了超时,但可以在遍历前增加行存在的断言,确保表格数据已加载完成,避免因异步渲染导致的元素未就绪问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:46:09