How do you wait on multiple XHR in Cypress that match the same intercept

Viewed 805

In my app after login in from a clean state, there are a series of sync queries that are being fired to make sure that the local data is updated. There is a loading screen while this is happening. I just need to cypress to wait for all these calls to finish before performing the test.

cy.intercept() is identifying the call, but cy.wait() only waits for the first one to be finished.

Is there a way to create the alias dynamilcally or have the application wait for the spinner to disapper?

enter image description here

describe('Navigation', function () {
beforeEach(function () {
    // Programmatically login via Amazon Cognito API
    cy.intercept('POST', '**/graphql').as('dataStore');
    cy.loginByCognitoApi(Cypress.env('cognito_username'), Cypress.env('cognito_password'));
    cy.wait(['@dataStore']);
});

it('shows logged in', function () {
    cy.get('[data-test=logo]').should('be.visible');
});
3 Answers

You can repeat wait on a single intercept, so count up the number of orange dataStore tags (looks like 11) and wait that amount of times

cy.intercept('POST', '**/graphql').as('dataStore');
cy.loginByCognitoApi(Cypress.env('cognito_username'), Cypress.env('cognito_password'));
Cypress._.times(11, () => {
  cy.wait('@dataStore')
})

Or it might be 10 - looking at the route defn. In any case, experiment. The app should be consistent in the calls it makes.

I had a similar case. What I do is store an array of objects in a different file and each object represents a specific test scenario. That way you can iterate through your test cases an assign an alias dynamically.

So you could do something like this:

beforeEach(function () {
   yourArray.forEach((testcase) => {
    cy.intercept('POST', '**/graphql').as(`${testcase.testname}datastore`);
    cy.loginByCognitoApi(Cypress.env('cognito_username'), 
    Cypress.env('cognito_password'));
    cy.wait(`@${testcase.testname}datastore`);
}
    
});

If the number of requests aren't consistent, something I've done is the following (I've since put this in a command to use in multiple places):

cy.intercept('POST', '**/graphql').as('dataStore');
cy.loginByCognitoApi(Cypress.env('cognito_username'),Cypress.env('cognito_password'));
cy.get('@dataStore.all').then(xhrs => cy.wait(Array(xhrs.length).fill('@dataStore')));

Doing a wait on the alias with "all" returns all of the calls made to aliased route that Cypress has seen since the alias was made.

Related