2

I have built something that can capture network requests and save them to a file. Currently I am now trying to build the second part which should return these captured requests, but running into some difficulties. Sometimes I have multiple requests going to a single method/url combination, and I need to return a different response depending on the request body. The problem I am facing is illustrated in the example below:

cy.route({
    url: 'api.example.com/**',
    method: myMethod,
    response: routeData => {
        // I can set the response here
        // But I don't have access to the request body
    },
    onRequest: xhr => {
        // I can access the request body here
        // But I am not supposed/able to set the response
    },
})

If I understand the API docs correctly, I am supposed to set the response in the response callback. However, in that callback I do not seem to have access to the XHR object from which I could read the request body.

Is there a way to access the request body in the response callback? Or, alternatively, is there a way to set the response from the onRequest callback?


Update: just saw this post which mentions a body property which can be added to the cy.route options object. I don't see this in the cypress route docs so I don't know if this is even a valid option, and I also wouldn't know if making multiple calls to cy.route with an identical method and url, but a different body would produce the correct results. If this was of any use, I would have hoped to have seen some branching logic based on a body property somewhere in this file, so I am not super hopeful.

Hendrik
  • 1,505
  • 3
  • 15
  • 20
  • I have come across: [Allow dynamic stubbing and responses](https://github.com/cypress-io/cypress/issues/521) which is still an open issue with `cypress`! I have myself tried 'few of the proposed work arounds' but nothing worked :( – Sree.Bh Jun 23 '20 at 12:46
  • Yeah I tried most of the proposed solutions too with similar results :-( – Hendrik Jun 24 '20 at 11:28
  • Did you read this [blog](https://dev.to/digitaledawn/how-to-use-stub-multiple-api-requests-dynamically-in-cypress-40g7) as well? It mentions a 'workaround' with `xhook`. – Sree.Bh Jun 24 '20 at 11:33
  • @Sree.Bh I have read that too, and have tried implementing it like that. I got to the point where I was returning fixture data from the `xhook.before` callback. I tried several ways of returning that data, i.e. just returning it as in the blog link you posted, and also using the second `callback` parameter as in this example: https://github.com/jpillora/xhook/blob/gh-pages/example/fake-response.html. Both approaches didn't work for me. Also this way we don't see the requests on the network tab anymore.... – Hendrik Jun 25 '20 at 14:29

1 Answers1

0

Cypress v6 comes with the cy.intercept API. Using that is much more convenient than using cy.server and cy.route.

Hendrik
  • 1,505
  • 3
  • 15
  • 20