Steve
Steve

Reputation: 297

Cypress: How to get response of fourth request from alias?

I have an interceptor that is getting a GET request for an endpoint that happens four times.

cy.intercept(`endpoint/data*`).as(
      'texasCounties'
);

This happens four times seen here. enter image description here

The only important one for me in the last request, however, when I wait for the response it only pegs the first one and I can't access the response body of the fourth request. Here is what I have so far

cy.wait('@texasCounties').then((interceptor) => {
       const res = interceptor.response.body
       cy.log(res) //only print object for the first request but I need the fourth
})

I've tried cy.wait('@texasCounties').eq(3) to get the fourth request but this does not work.

Does anyone know how to do this?

Upvotes: 0

Views: 788

Answers (1)

jjhelguero
jjhelguero

Reputation: 2565

If you only want need the last call, you can move your intercept just before the call is made.

With your attempt, you were close to the answer. You'll have to use .get('@alias') to get all intercepted requests and access the last one using .its(). This is what it will look like.

// intercept and other test code

cy.get('@texasCounties.all') // this will get all four intercepted requests
  .then(console.log) // if you want to log
  .should('have.length', 4) // you can make assertions 
  .its(3) // to access the fourth request

Upvotes: 1

Related Questions