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

如何在Cypress中获取指定投资者的产品列表并实现校验?

问题分析与解决方案

原代码无法正常工作的核心问题有三点:

  • 在同步的map方法中使用异步Cypress命令,导致返回的是命令对象而非实际文本值
  • 引用别名时错误使用cy.wrap('@productList'),正确方式应为cy.get('@productList')
  • 未处理HTML文本中的多余空格,可能导致includes判断失效

修正后的核心方法

/**
 * Returns a list of products for the investor passed
 * @param {string} investor 
 * @return {Cypress.Chainable<Array<string>>} list of trimmed product names
 */
getListOfProductsAlreadyPresent(investor) {
  // 定位所有包含指定投资者的行,再提取对应产品列的文本
  return cy.get('tr[role="row"]').filter((index, row) => {
    return Cypress.$(row).find('td[aria-colindex="1"] div.d-flex').text().trim() === investor;
  }).then($rows => {
    // 同步提取每一行的产品文本并去空格
    return Cypress.$.makeArray($rows).map(row => {
      return Cypress.$(row).find('td[aria-colindex="2"]').text().trim();
    });
  });
}

修正后的调用代码

检查并添加产品

this.getListOfProductsAlreadyPresent(investor).as('productList');
cy.get('@productList').then((list) => {
  if (!list.includes(sourceProduct.trim())) {
    this.setSourceProductIfNotPresent(investor, sourceProduct, true);
  }
});

添加后的校验代码

this.getListOfProductsAlreadyPresent(investor).then((list) => {
  if (!list.includes(sourceProduct.trim())) {
    throw new Error(`Source product ${sourceProduct} did not get added successfully for investor ${investor}`);
  }
});

关键优化点说明

  • 同步DOM操作:在.then回调中直接用jQuery处理DOM元素,避免异步命令干扰数组返回
  • 精准行过滤:通过aria-colindex属性定位列,比:contains更精准(避免文本部分匹配的问题)
  • 文本去空格:对所有提取的文本执行trim(),消除HTML中换行和空格导致的匹配失败
  • 正确引用别名:使用cy.get('@productList')获取异步返回的数组值,而非cy.wrap

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:53:24