Cypress中循环调用cy.request后Record类型变量未定义问题求助
解决Cypress异步请求结果收集与后续调用问题
问题根源
- 变量未初始化:
idsWithValue仅声明未赋值为{},导致在回调中赋值时会抛出"Cannot set property of undefined"错误。 - 异步执行顺序问题: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
相关产品推荐
相关产品推荐

