Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress: how to wait for all requests to finish

Tags:

cypress

I am using cypress to test our web application.

In certain pages there are different endpoint requests that are executed multiple times. [ e.g. GET /A GET /B GET /A].

What would be the best practise in cypress in order to wait for all requests to finish and guarantee that page has been fully loaded.

I don't want to use a ton cy.wait() commands to wait for all request to be processed. (there are a lot of different sets of requests in each page)

like image 982
mXeIn Avatar asked Nov 03 '20 11:11

mXeIn


2 Answers

I'm sure this is not recommended practice but here's what I came up with. It effectively waits until there's no response for a certain amount of time:

function debouncedWait({ debounceTimeout = 3000, waitTimeout = 4000 } = {}) {
  cy.intercept('/api/*').as('ignoreMe');

  let done = false;
  const recursiveWait = () => {
    if (!done) {
      // set a timeout so if no response within debounceTimeout 
      // send a dummy request to satisfy the current wait
      const x = setTimeout(() => {
        done = true; // end recursion

        fetch('/api/blah');
      }, debounceTimeout);

      // wait for a response
      cy.wait('@ignoreMe', { timeout: waitTimeout }).then(() => {
        clearTimeout(x);  // cancel this wait's timeout
        recursiveWait();  // wait for the next response
      });
    }
  };

  recursiveWait();
}
like image 81
John Leonard Avatar answered Oct 06 '22 18:10

John Leonard


You can use the cy.route() feature from cypress. Using this you can intercept all your Get requests and wait till all of them are executed:

cy.server()
cy.route('GET', '**/users').as('getusers')
cy.visit('/')
cy.wait('@getusers')
like image 43
Alapan Das Avatar answered Oct 06 '22 20:10

Alapan Das