0
0
Cypresstesting~15 mins

cy.scrollTo() in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify scrolling to the bottom of a long page
Preconditions (1)
Step 1: Open the web page URL 'https://example.com/long-page'
Step 2: Scroll to the bottom of the page using the scroll bar or mouse wheel
Step 3: Observe the page content at the bottom
✅ Expected Result: The page scrolls smoothly to the bottom, and the footer element with id 'footer' is visible
Automation Requirements - Cypress
Assertions Needed:
Verify the page scrolls to the bottom
Verify the footer element with id 'footer' is visible after scrolling
Best Practices:
Use cy.scrollTo() with 'bottom' argument to scroll
Use cy.get() with proper selector for footer
Use .should('be.visible') assertion to confirm visibility
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Scroll to bottom test', () => {
  it('should scroll to the bottom and verify footer visibility', () => {
    cy.visit('https://example.com/long-page');
    cy.scrollTo('bottom');
    cy.get('#footer').should('be.visible');
  });
});

The test opens the long page URL using cy.visit(). Then it uses cy.scrollTo('bottom') to scroll the page to the bottom smoothly. After scrolling, it locates the footer element by its id #footer using cy.get(). Finally, it asserts that the footer is visible on the screen with .should('be.visible'). This confirms the scroll action worked as expected.

Common Mistakes - 3 Pitfalls
Using hardcoded waits like cy.wait(5000) before checking footer visibility
{'mistake': "Using incorrect selector like cy.get('.footer') when footer has id 'footer'", 'why_bad': 'Wrong selectors cause tests to fail because elements are not found', 'correct_approach': "Use accurate selectors matching the actual element attributes, e.g., cy.get('#footer')"}
Not using cy.scrollTo() and trying to scroll by triggering keyboard events
Bonus Challenge

Now add data-driven testing to scroll to different positions: 'top', 'center', and 'bottom' and verify footer visibility only at 'bottom'

Show Hint