0
0
Cypresstesting~5 mins

cy.scrollTo() in Cypress

Choose your learning style9 modes available
Introduction

We use cy.scrollTo() to move the page view to a specific spot. This helps us test parts of a page that are not visible without scrolling.

When you want to test a button or link that is below the visible area of the page.
When you need to check if a footer or header appears correctly after scrolling.
When testing lazy-loaded images or content that appear only after scrolling.
When verifying that scrolling triggers certain animations or events.
When automating user actions that require scrolling to a specific section.
Syntax
Cypress
cy.scrollTo(position, options)

// position can be a string like 'top', 'bottom', 'left', 'right', 'center'
// or an object with x and y coordinates like { x: 0, y: 250 }
// options is an optional object for animation and easing

The position argument tells Cypress where to scroll.

You can scroll instantly or with animation by setting options.

Examples
This scrolls the page all the way down to the bottom.
Cypress
cy.scrollTo('bottom')
This scrolls the page back up to the top.
Cypress
cy.scrollTo('top')
This scrolls vertically 500 pixels down from the top.
Cypress
cy.scrollTo({ x: 0, y: 500 })
This scrolls smoothly to the center of the page over 1 second.
Cypress
cy.scrollTo('center', { duration: 1000, easing: 'linear' })
Sample Program

This test opens a page, scrolls to the bottom, and checks if the footer is visible.

Cypress
describe('Scroll test example', () => {
  it('scrolls to bottom and checks footer visibility', () => {
    cy.visit('https://example.cypress.io')
    cy.scrollTo('bottom')
    cy.get('footer').should('be.visible')
  })
})
OutputSuccess
Important Notes

Use cy.scrollTo() to simulate real user scrolling behavior.

Scrolling can be animated or instant; animation helps test smooth scrolling effects.

Always check if the element you want to interact with is visible after scrolling.

Summary

cy.scrollTo() moves the page view to a specific position.

It helps test elements that appear only after scrolling.

You can scroll by position name or exact coordinates, with optional animation.