cypresscypress-intercept

Using Cypress how can intercept then wait for x amount of request to complete?


The site I'm working on makes multiple requests to api/v1/roles/{UUID}/permission-groups?includeUnlinked=true to load all the permissions that could be applied to a user.

If I use cy.intercept('api/v1/roles/*/permission-groups?includeUnlinked=true').as('permissions') then wait, Cypress continues as soon as the first request has completed. Unfortunately, not all the permissions have loaded by then, so my test fails. I'm having to hard code a 2-second wait just to make sure all the permissions have loaded, which obviously isn't ideal.

How can I make my test intercept and wait until all the permissions have loaded?


Solution

  • Go to the browser devtools, open the Network tab, clear the display and run the test.

    Count the number of permission-groups entries to figure out how many permissions there actually are loaded (it should be consistent each run), then apply the intercept wait() that many times.

    Cypress._.times(5, (index) => cy.wait('@permissions'))  
    // wait 5 times if there are 5 permissions
    

    If you find that difficult, or the permissions are not applied consistently (which may be bug in itself), you can wait for network-idle.

    cy.waitForNetworkIdle('/v1/api/roles/*/permission-groups?includeUnlinked=true', 1000)
    

    although this would not appear to be necessary in this case.