Cypress scrolling behaviour on `get` and relative positionning

Viewed 4824

When calling Cypress cy.get method, the page is scrolled so that the selected element is at the top of the page.

This is problematic when there is a relatively positioned sticky toolbar on top of it, because it may systematically hide the element and thus fail the further click events.

This is reproducible with Material UI "Dashboard" template for instance.

Any idea how I could solve this, either by modifying the template to keep a sticky top menu without relative positionning (edit: actually the header is absolutely positionned), or setting up Cypress to slightly offset the scroll when getting elements?

Of course I can force clicks with cy.click({force:true}) but that's not very good in the long run.

3 Answers

This scrolling logic only applies to commands that are actionable above. We do not scroll elements into view when using DOM commands such as cy.get() or .find(). Because of this

disable scroll in the click command

.click({scrollBehavior:false})

As you said, the page is scrolled so that the selected element is at the top of the page.

Cypress docs:

Before interacting with an element, we will always scroll it into view (including any of its parent containers). Even if the element was visible without scrolling, we perform the scrolling algorithm in order to reproduce the same behavior every time the command is run.

But you can get around this if it's causing problems with your test by adding {scrollBehavior:false} to the click command.

Section of the docs

You can use the .pause() method to see if .get() actually scroll the page. According to the documentation, page is never scrolled when using .get(), only when using action commands (like `.click() source).

FYI there is a feature request to change the scrolling behaviour.

Also, there is a cheeky workaround you could use in every test:

Cypress.on('scrolled', $el => {
  $el.get(0).scrollIntoView({
    block: 'center',
    inline: 'center'
  });
});
Related