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

Cypress中循环调用cy.request后Record类型变量未定义问题求助

解决Cypress异步请求结果收集与后续调用问题

问题根源

  1. 变量未初始化:idsWithValue仅声明未赋值为{},导致在回调中赋值时会抛出"Cannot set property of undefined"错误。
  2. 异步执行顺序问题:Cypress的cy.request是异步命令,会被加入Cypress的命令队列延后执行;而同步代码submitRequest(idsWithValue)会在所有异步请求完成前直接运行,此时idsWithValue还未被赋值,自然是undefined。

解决方案

方案一:用Promise.all等待所有请求完成

通过收集所有请求的Promise,等待全部执行完成后再调用submitRequest:

// 初始化变量,避免undefined报错
let idsWithValue: Record<string, commonType.Information> = {};

// 构建所有请求的Promise数组
const requestTasks = Object.entries(information).map(([_, info]) => {
  const requestBody = {
    name: info.Name, // 修正原代码的字符串模板错误,取当前项的Name
    description: info.Description // 同理修正Description
  };

  const options = {
    method: 'POST',
    url,
    body: requestBody,
    headers: coApi.getRequestHeaders()
  };

  // 返回每个请求的处理逻辑,同时保存结果到idsWithValue
  return cy.request(options).then((response) => {
    expect(response.status).to.eq(200);
    const informationId: string = response.body;
    idsWithValue[informationId] = info;
  });
});

// 等待所有请求完成后执行submitRequest
cy.wrap(Promise.all(requestTasks)).then(() => {
  submitRequest(idsWithValue);
});

方案二:用Cypress的cy.each遍历(更贴合Cypress风格)

利用Cypress的cy.each命令遍历数据,确保所有请求都在命令队列中执行完成后再触发后续操作:

let idsWithValue: Record<string, commonType.Information> = {};

// 将对象转为数组后用cy.each遍历
cy.wrap(Object.entries(information)).each(([_, info]) => {
  const requestBody = {
    name: info.Name,
    description: info.Description
  };

  const options = {
    method: 'POST',
    url,
    body: requestBody,
    headers: coApi.getRequestHeaders()
  };

  cy.request(options).then((response) => {
    expect(response.status).to.eq(200);
    const informationId: string = response.body;
    idsWithValue[informationId] = info;
  });
}).then(() => {
  // 所有遍历和请求完成后执行submitRequest
  submitRequest(idsWithValue);
});

额外注意事项

  • 原代码中requestBody的name和description使用了information.Name字符串模板,这会直接把字符串"information.Name"作为请求参数,而非取对应数据项的属性值,必须修正为info.Name或information[index].Name。
  • 若information是数组而非对象,可直接用cy.wrap(information).each((info) => {...})遍历,无需Object.entries转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:22:33