简体   繁体   English

如何从 for 循环返回值 in.then function in Cypress

[英]How to return value from for loop in .then function in Cypress

//command.ts
Cypress.Commands.add("getRunID"): any => {
return cy.getData().then((response: any) => {     
      var JsonResponse: any = response.body;
      var id: any = [];
      for (var i = 0; i < JsonResponse.Items.length; i++) {
        id[i] = JsonResponse.Items[i].Id;
      }
    
      var runID: any;
//looping through previous response id and passing that into URL(each id i am checking response , where the response is not null,I will get the runID)
      for (var i = 0; i < id.length; i++) {     
        let url = "**url+id[i]**"      
        cy.request({
          method: "Get",
          url: url,
          headers: {
            "Content-Type": "application/json",
            accept: "application/json",
          },
        }).then((response) => {
          
          if (response.body.Items.length !== 0) {  //condition for fetching runID 
            var runId = response.body.Items[0].Id;
            return runId;  **//not returning value**         
          }
        });
      } //for loop end
 });
}

//Test.ts -test file
cy.getRunID().then((result)=>{console.log(result)})

I want to return runId from method getRunID (which is a command in command.ts).我想从方法getRunID (这是 command.ts 中的命令)返回runId

I think the problem is runId is set inside the if loop and I am not able to return this id as the for loop keeps running.我认为问题是runId是在if循环中设置的,我无法返回这个 id 因为 for 循环一直在运行。

As a consequence a null id is returned.结果返回了null id。 How can i solve this?我该如何解决这个问题?

You can't mix asynchronous commands cy.request() and synchronous loops, because the code needs to wait for requests to finish.您不能混合使用异步命令cy.request()和同步循环,因为代码需要等待请求完成。

So, at the end make a cy.then() call to do the wait for all prior cy.request() , then do a cy.wrap() to make runId the result of the command.因此,最后调用cy.then()来等待所有之前的cy.request() ,然后调用cy.wrap()使runId成为命令的结果。

Cypress.Commands.add("getRunID") => {
    ...

  } //for loop end
  cy.then(() => {   <-- now requests are finished
    cy.wrap(runId)  <-- set the command result
  })
}) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM