How to ensure order of Cypress request execution

Viewed 543

In my Cypress test, I am trying to make calls to two seperate API endpoints.

I'm able to make the calls, but I need to ensure they execute in the correct order.

Below are simplified versions of my requests:

cy.request('POST', apiUrl + 'Session', {username: merchant_username}
).as('postSession')

cy.request('POST', apiUrl + 'TestCase', {username: merchant_username}
).as('postTestCase')

It's important that the calls execute in this order because some of them depend on values from the others.

I am trying to retrieve sessionId from the postSession response:

cy.request({
      method: 'POST',
      url: apiUrl + 'session',
}).as('postSession')

cy.get('@postSession').should(response => {
         sessionId = response.body.SessionId;
})

And then use it in the request body of postTestCase:

cy.request({
            method: 'POST',
            url: apiUrl + 'TestCase',
            body: {
              "SessionId": sessionId
            }
})

If I do .then() after postSession & place postTestCase inside that like so, the request works fine, but I would like to avoid doing that if possible.

cy.get('@postToken').should(response => {
         sessionId = response.body.SessionId;
}).then(() => {
  cy.request({
  method: 'POST',
  url: apiUrl + 'TestCase',
  body: {
        "SessionId": sessionId
        }
    })
})

I've also tried using cy.wait(), but the sessionId is blank in the 2nd request then.

cy.wait('@postSession')
cy.wait('@postTestCase')

Is there a way I can ensure postSession is executed before postTestCase without placing postTestCase inside a .then() after postSession?

2 Answers

You need to do something like this:

cy.request({
            method: 'GET',
            url: 'https://' + host + '/lending/loan',
            headers: default_headers
        }).then(res => {
             cy.request({})
                .then(res => {})
        })

Unfortunately, at the time this answer is posted, there is an open issue on the Cypress GitHub repository with a proposal for await, as per this link.

So only the "nested" requests way is possible at the moment.

For example of your snippets:

cy.request({
  method: 'POST',
  url: apiUrl + 'session',
}).then((response) => {
  const sessionId = response.body.SessionId;
  
  cy.request({
    method: 'POST',
    url: apiUrl + 'TestCase',
    body: {
      "SessionId": sessionId
    },
  });
});
Related