Intercepting specific XHR request when there are more than one request with the same URL

Bothi Palani
2 min readOct 5, 2023

This story is about using network wait in end to end automation tests.

when I was working for an end to end cypress tests for one of the projects, some tests were flaky because of test was looking for elements in the page but page is not loaded with the expected elements. There may be delay when Front end sends a query to get the data from Back end.

How can we wait for the request to be completed and continue with the next steps ?

Cypress framework has intercept which can be used to wait for the network (xhr) requests. However what if there are more than one request with the same url but with different payloads needs to be intercepted ?

In my project, login users are created on AWS cognito user pool. Challenge for automation is to extract the Auth Token from one of the requests ( all the aws cognito login request URL looks the same except the headers and payload ) and store the token for using in API requests.

For example, when you look at the network tab after click on the login button there would be few request with this URL, https://cognito-idp.eu-west-1.amazonaws.com/

However I have to intercept the request with the header value, ‘X-Amz-Target’: ‘AWSCognitoIdentityProviderService.RespondToAuthChallenge’ and request body contains specific challenge name.

Following is the code snippet used to intercept the specific request.

cy.intercept(
{
method: 'POST',
url: 'https://cognito-idp.eu-west-1.amazonaws.com/',
headers: {
'X-Amz-Target': 'AWSCognitoIdentityProviderService.RespondToAuthChallenge',
},
},
req => {
if (req.body.ChallengeName === 'NEW_PASSWORD_REQUIRED') {
req.alias = 'token';
}
},
);
cy.wait('@token').then(({ response }: any) => {
const authToken = response.body.AuthenticationResult.AccessToken;
});

--

--