Search code examples
apicallbackcypresscypress-custom-commands

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).

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.

As a consequence a null id is returned. How can i solve this?


Solution

  • You can't mix asynchronous commands cy.request() and synchronous loops, because the code needs to wait for requests to finish.

    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.

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