Search code examples
javascripttypescriptintegration-testingcypresse2e-testing

Keep scrolling down while loading in cypress


I have a page that has an element where if you scroll down, it loads new data.

This takes about 10 seconds.

I have written the following test:

it('Should display at least one facility in booking panel', (done) => {
  function recursivelyScroll() {
    cy.get(element)
      .scrollTo('bottom');

    cy.get(element)
      .then($el => {
        // If the element contains a loading class, we wait one second and scroll down again
        if ($el.find(Loading).length > 0) {
          setTimeout(recursivelyScroll, 1000);
        } else {
          // We are done waiting, no more loading is needed
          // write test here

          done();
        }
      });
  }
  recursivelyScroll();
});

CypressError

Timed out after 4000ms. The done() callback was never invoked!

The done() method is not called fast enough according to Cypress, but they have no documentation on how to extend the done time period. Also, there might be a better way that I'm unaware of to create this scrollbehaviour in Cypress. Is there an easy fix?


Solution

  • Have you tried using the recursion plugin in cypress?

    It would look something like this:

    cy.get(element).scrollTo('bottom');
    recurse(
        () => cy.contains('element', 'Loading').should(() => {}),
        ($quote) => $quote.length > 0 ,
        {
          limit: 300,
          log: false,
          post(){
            setTimeout(recursivelyScroll, 1000);
          }
        },
    )
    

    The idea was taken here: https://www.youtube.com/watch?v=KHn7647xOz8 Here example how to use and install https://github.com/bahmutov/cypress-recurse