I’m kind of new on Cypress intercept
, but I am in need of capturing the response to a GET message, but wait for the message which has a response body with a specific value on its body.
For example, I may be receiving two responses to two GET requests, such as these two:
Event: request
cypress_runner.js:190995 Resource type: xhr
cypress_runner.js:190995 Method: GET
cypress_runner.js:190995 Url: https://127.0.0.1/api/users/61a68c4a1d2c5258baece19c?_=1638304841558
cypress_runner.js:190995 Matched `cy.intercept()`: {RouteMatcher: {…}, RouteHandler Type: 'Spy', RouteHandler: undefined, Request: {…}, Response: {…}, …}
cypress_runner.js:190995 Response status code: 200
cypress_runner.js:190995 Response headers: {date: 'Tue, 30 Nov 2021 20:40:43 GMT', Content-Encoding: 'gzip', server: 'nginx', Vary: 'Accept-Encoding', access-control-allow-methods: 'PUT, GET, POST, DELETE, OPTIONS, PATCH', …}
cypress_runner.js:190995 Response body: {"name": "Alice", "description": "Created by Cypress"}
Event: request
cypress_runner.js:190995 Resource type: xhr
cypress_runner.js:190995 Method: GET
cypress_runner.js:190995 Url: https://127.0.0.1/api/users/61a68c4a1d2c5258baece19c?_=1638304841558
cypress_runner.js:190995 Matched `cy.intercept()`: {RouteMatcher: {…}, RouteHandler Type: 'Spy', RouteHandler: undefined, Request: {…}, Response: {…}, …}
cypress_runner.js:190995 Response status code: 200
cypress_runner.js:190995 Response headers: {date: 'Tue, 30 Nov 2021 20:40:43 GMT', Content-Encoding: 'gzip', server: 'nginx', Vary: 'Accept-Encoding', access-control-allow-methods: 'PUT, GET, POST, DELETE, OPTIONS, PATCH', …}
cypress_runner.js:190995 Response body: {"name": "Bob", "description": "Created by Cypress"}
My intercept for now looks like this:
cy.intercept("GET", "/api/users/*").as("waitingForUpdateOnAlice")
cy.wait("@waitingForUpdateOnAlice")
But if the server returns the answer for Bob, then I don’t have the chance of continue waiting.
Is there a way to handle this?
Mention: I do NOT have control or access to the trailing id on the url, so I do need to do this filtering only upon the response body.
2
Answers
You can alias an individual request. This should accomplish what you’d like.
You might need to play around with the exact form of that
req.body.name
conditional.First of all, declare a function to be used recursively:
then in your test section: