Search code examples
typescriptcommandcypress

Cypress cy.request response store in record type typescript


I'm working on some Cypress tests where I need to add some information to a database via an api call. But I need all the IDs from the response to pass to another request within Cypress but I need to do it outside the for loop as I don't want to make the request everytime we have information. I've created a record type and added a value within the .then but it is still undefined. The parameter within the submitRequest call is undefined. Has anyone come across this before? I can't call the submitRequest method within the cy.request then body as it has to be outside the for loop. Below is the code

    let idsWithValue: Record<string, commonType.Information>;
    
    for (let index in information) {
        //Create the request
        const requestBody = {
            name: `information.Name`,
            description: `information.Description`
        }


        //Send request for elements
        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;
            //After we get the informationId from server add it to a list to pass to another request method
            idsWithValue[informationId] =information[index];
           
        })
    }

    //Submit  request (idsWithValueis undefined here) this has to be outside for loop
    submitRequest(idsWithValue);```


Solution

  • You should be able to fix it by making sure you only call submitRequest() after all cy.request() in the loop have completed.

    Try wrapping the call in a cy.then(), I'm not 100% sure without running a test but usually Cypress won't execute a command until all the previous commands are finished,

    const idsWithValue = [];
    for (...) {
      cy.request(...).then(response => {
        idsWithValue[...] = ...
      })
    }
    
    cy.then(() => {
      submitRequest(idsWithValue)
    })