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

Time:07-13

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!

CodePudding user response:

Please use Async/await : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

async function getData() {
  let response = await cy.request('GET', myUrl).its('body')
  let subResponse = await cy.request('GET', response).its('body')
  let subSubRes = await cy.request('GET', subResponse).its('body')
  expect(subSubRes, myMessage).to.eq(myEvaluation)
}

CodePudding user response:

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.

(Or async-await pattern).

CodePudding user response:

Use async and await

const asyncFunc = async () => {
    try {
        const res = await cy.request('GET', myUrl).its('body')

        const subRes = await cy.request('GET', res).its('body')

        const subSubRes = await cy.request('GET', subRes).its('body')

        expect(subSubRes, myMessage).to.eq(myEvaluation)
    } catch (error) {
        // Handle error
    }
}

asyncFunc()
  • Related