I am working on a Cypress test where multiple requests are sent to the same URL but with different body content. Specifically, the test changes the input values in the UI, which triggers a new request to the server. The problem arises when attempting to validate the request body of each individual request using cy.wait() in combination with cy.intercept().
The structure of the test code is roughly as follows:
cy.intercept("POST", "/url").as("getCall");
cy.wait("@getCall").should((interception) => {
// validation the body for the first request
});
// UI interactions that trigger a new request`
cy.wait("@getCall").should((interception) => {
// validation for the body with new value for second request
});
The issue is that the second cy.wait() still gets the body from the first request, leading to failed assertions.
A workaround I’ve found is to give a different alias for the intercept on each request.:
cy.intercept("POST", "/url").as("getFirstCall");
cy.wait("@getFirstCall").should((interception) => {
// validation for the first request
});
// UI interactions that trigger a new request
cy.intercept("POST", "/url").as("getSecondCall");
cy.wait("@getSecondCall").should((interception) => {
// validation for the second request
});
This works but is a bit clumsy. Is there a better way to handle multiple requests to the same URL using cy.intercept() and cy.wait()?
2
Answers
You can alias individual requests, which will allow you to write one singular intercept, and give the different requests different aliases.
Alternatively, you can get all requests that are intercepted by appending
.all
onto the alias., or a specific intercept by appending a 1-indexed number (.2
for the second, for example). Note: there is some discussion on how public and available.all
and.[x]
are and if Cypress continues to support these going forward, so be aware if implementing these.IMO there’s nothing really wrong with your workaround, but you could simplify it by numbering the aliases.
This way you should be guaranteed the first call occurs for the first wait, etc.
I am surprised that you are getting this problem – the initial code looks like it should work properly. Is there any further detail you can give, since I’m wondering it there’s another issue at play here?