1

How could I scroll one page to the right in Cypress?

E.g. I have a horizontally scrollable area. The area contains elements a, b and if I scroll to the right a and b get destroyed, while c and d get added.

My attempt is to find out the width of the scrollable view and then scroll that amount to the right. But the width does not get retrieved before the scrollTo gets called.

Here is what I am trying to do:

const width = cy.getCy("scroll-viewport").invoke("width");
cy.getCy("scroll-viewport").scrollTo(width, 0);
Fody
  • 23,754
  • 3
  • 20
  • 37
manymanymore
  • 2,251
  • 3
  • 26
  • 48

1 Answers1

2

Your code sample has some mystery about it, for example what is cy.getCy().

I can show you how to do it with standard code, and you can adapt from there.

Assuming scroll-viewport is a selector for the scroll container (the owner of the scroll bar)

cy.get("scroll-viewport").then($scrollContainer => {
  const width = $scrollContainer[0].offsetWidth;
  $scrollContainer[0].scrollTo(width, 0);
})

Note $scrollContainer[0].scrollWidth gives you the total width after scrolling, in case you need that.

Fody
  • 23,754
  • 3
  • 20
  • 37
  • Just one more clarification. What if I want to continue chaining my Cypress commands after that, what could I do? I.e. can I put a command after the `then` and expect it to wait until the `scrollTo` inside the `then` will finish working? E.g. `cy.get(...).then(...).get("foo").click();`. Or will the `get("foo").click()` part run before the scrolling will end? – manymanymore Jun 24 '22 at 12:27
  • Commands are put in a queue and each is run to completion before the next starts. Except if code inside a `.then()` is async, then you have to return a Promise and Cypress will wait for the promise to resolve. But pretty sure `.scrollTo(width, 0)` is synchronous so you don't have to worry. – Fody Jun 24 '22 at 19:41
  • BTW `cy.get(...).then(...).get("foo").click();` is the same as `cy.get(...).then(...); cy.get("foo").click();`. Both queue the same commands. – Fody Jun 24 '22 at 19:42