Search code examples
javascriptautomated-testscypresse2e-testing

How to avoid .then() nesting when working with API Calls in Cypress?


With my team we're trying to find a more readable way to handle dependent API calls in Cypress. We have some code just like this nowadays:

// nested code
      cy.request('GET', myUrl).its('body').then(res => {
        cy.request('GET', res).its('body').then(subRes => {
          cy.request('GET', subRes).its('body').then(subSubRes => {
            expect(subSubRes, myMessage).to.eq(myEvaluation);
          })
        })
      })

We have thought about this solution also but I think we doesn't gain a lot in readability.

// less nested code?
      let response;
      let subResponse;
      cy.request('GET', myUrl).its('body').then(res => {
        response = res;
      })
      
      cy.then(() => {
        cy.request('GET', response).its('body').then(subRes => {
          subResponse = subRes;
        })
      })

      cy.then(() => {
        cy.request('GET', subResponse).its('body').then(subSubRes => {
          expect(subSubRes, myMessage).to.eq(myEvaluation);
        })
      })

Do you have any ideas to handle this kind of logic without getting into a pyramid? Thanks in advance!


Solution

  • Something like

    cy.request('GET', myUrl).its('body')
        .then(res => cy.request('GET', res).its('body'))
        .then(subRes => cy.request('GET', subRes).its('body'))
        .then(subSubRes => {
            expect(subSubRes, myMessage).to.eq(myEvaluation);
        });
    

    should work.