alTimewax
alTimewax

Reputation: 53

Difficulties with Cypress scrollTo method

I am having a few issues testing a virtual scroll component with Cypress. I have a test that checks the li elements present in the DOM after scrolling to the bottom of a container.

When written like this the test passes:

cy.get('.virtual-scroll').scrollTo('bottom')
cy.wait(0)                                             
cy.get('li').last().children('h4').contains('1999')

When written like this it doesn't:

cy.get('.virtual-scroll').scrollTo('bottom')
cy.get('li').last().children('h4').contains('1999')

This also fails:

cy.get('.virtual-scroll').scrollTo('bottom').get('li').last().children('h4').contains('1999')

In the second and third examples, get('li') is returning the li elements present before the scroll has completed, and therefore failing the test. I can fix this by adding .wait, but don't fully understand the behaviour and wonder if this is a bug.

Any ideas?

Upvotes: 5

Views: 28278

Answers (2)

bgeffrault
bgeffrault

Reputation: 148

In my case, adding a duration to the scroll option did the trick. cy.get("@dialogContent").scrollTo("center", { duration: 500 });

Upvotes: 0

kuceb
kuceb

Reputation: 18043

Make an assertion that will always pass when the DOM is rendered, such as using .get() for an element that gets added to the DOM

ex) if you had a <ul class="myloadedlist">.... :

cy.get('.virtual-scroll').scrollTo('bottom')
cy.get('ul.myloadedlist')
cy.get('li').last().children('h4').contains('1999')

That way, Cypress will continue with the test as soon as that element becomes visible.

Why?

I'm assuming the elements get added to the DOM in some sort of scroll eventListener. In that case this is correct behavior.

Essentially what you've tested is the race condition of a user scrolling very quickly to the bottom of the page, to see that the DOM has not yet finished rendering- a valid senario.

Since you targeted the last() li element, Cypress finds the last element of the page before the DOM gets updated, and expects it to contain 1999, which it does not, even after Cypress retries for 4 seconds.

This is actually a great feature of Cypress, because you can test on the state of the DOM at times that the User might only see for a split second.

Upvotes: 14

Related Questions