Randy
Randy

Reputation: 9809

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?

Upvotes: 2

Views: 2680

Answers (2)

Liana
Liana

Reputation: 26

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

Upvotes: 1

Fseee
Fseee

Reputation: 2631

Try to switch to When assertion and declare that function outside the execution:

When('Should display at least one facility in booking panel', (done) => {
    recursivelyScroll(done)
}

function recursivelyScroll(done){
    //see implementation below
}

Not sure how about which "Loading" is, maybe you have to put into double quotes?

Moreover please note that cypress is asynchronous, then the scrollTo and the then code sections are executed at same time in your code, just use then after the scroll.

And I will change the setTimeout into cy wait function before executing recursion, give a try to below code:

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

Upvotes: 1

Related Questions