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

Cypress中cy.each()无法处理数组:调用getOperationData后遇对象类型错误

解决Cypress cy.each() 数组类型错误的方案

问题原因

你自定义的getOperationData命令没有返回过滤后的测试数据数组,导致cy.each()接收到的不是数组类型的subject,而是Cypress命令链的默认对象,从而触发错误。

修复步骤

修改getOperationData命令,确保它返回过滤后的数组作为命令链的subject:

Cypress.Commands.add('getOperationData', (mode, operationsArrayName = 'operations') => {
  // 返回整个命令链,确保传递过滤后的数组到下一个命令
  return cy.fixture('alerts-escalation-param.params.json').then((params) => {
    const fixturePath = params[operationsArrayName];
    // 返回fixture读取结果,传递到下一个then
    return cy.fixture(fixturePath).then((data) => {
      const opData = data.filter((element) => element.mode === mode);
      Cypress.env('fixtureData', opData);
      // 返回过滤后的数组,作为cy.each()的处理对象
      return opData;
    });
  });
});

额外注意事项

测试用例中的cy.should调用存在语法问题,断言必须绑定到具体的DOM元素或Cypress对象,例如:

// 错误写法
cy.should('equal', searchCase.expectedRowsCountResult)

// 正确写法(示例)
cy.get('.result-row-count').should('have.text', searchCase.expectedRowsCountResult)

另外,cy.getdefaultOperationExpectedValue()如果是异步命令,需要用.then()处理返回值:

cy.getdefaultOperationExpectedValue().then((expectedValue) => {
  cy.get('.empty-row').should('have.length', expectedValue.numberOfColumnsOnEmptyRow)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:57:04