I have a Cypress test in which I navigate to a particular page and that page automatically initiates multiple requests. One of the requests fetches the data and displays it on the UI. In my test, I want to capture that request with all the parameters and headers and replay the same after I click on the log-out button. With this test, I want to ensure that authorized requests return an error code if they are called again with the same authentication headers (cookies) after log-out. I am not even sure if this is possible via Cypress or not. As of now, I do this test manually using tools like Fiddler, Burp Repeater, etc., and want to automate it. Suggestions regarding any other ways to make such tests automatable are also acceptable.
Asked
Active
Viewed 186 times
1
-
When you say "replay it" do you mean sending another request? If so, you can do it with cy.request(). – jjhelguero Dec 09 '22 at 16:11
-
Yeah, I meant sending the same request again. – Sunny Dec 12 '22 at 02:56
2 Answers
3
First, capture a request sent by the app with cy.intercept()
. Then use cy.request()
to re-send it.
You want to pass the test if the last request fails, so I would try it with the failOnStatusCode: false
.
The basic pattern would be as follows.
cy.intercept(url, (capturedRequest) => {
cy.request({
...capturedRequest,
failOnStatusCode: false
})
.then(response => {
expect(response.statusCode).to.eq(505) // whatever the failure code is
})
});
cy.get(logoutSelector).click()

Paolo
- 3,530
- 7
- 21
1
Paolo's answer won't work because capturedRequest
will always be undefined
. Cypress is asynchronous, so the variable won't have a value by the time cy.request()
is called, causing it to fail.
The proper way to do this would be:
cy.intercept('*/logout*').as('outRequest'); // Setup intercept and alias to monitor the request
cy.get('#logoutButton').click(); // Initiate the request
cy.wait('@outRequest'); // Wait for the request to come back, this is important
// Resend request and validate status code
cy.get('@outRequest').then((out) => {
cy.request({...out.request, failOnStatusCode: false}).should(response => {
expect(response.status).to.eq(401)
})
})

DJSDev
- 812
- 9
- 18