0
0
Cypresstesting~15 mins

cy.viewport() for screen sizes in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify website layout changes on different screen sizes using cy.viewport()
Preconditions (2)
Step 1: Open the test website homepage
Step 2: Set viewport to 320x480 (mobile size) using cy.viewport()
Step 3: Verify that the mobile menu button is visible
Step 4: Set viewport to 768x1024 (tablet size)
Step 5: Verify that the navigation bar is visible
Step 6: Set viewport to 1280x800 (desktop size)
Step 7: Verify that the full navigation menu is visible
✅ Expected Result: The website layout changes according to the viewport size, showing mobile menu on small screens and full navigation on larger screens.
Automation Requirements - Cypress
Assertions Needed:
Check visibility of mobile menu button at 320x480
Check visibility of navigation bar at 768x1024
Check visibility of full navigation menu at 1280x800
Best Practices:
Use cy.viewport() to simulate different screen sizes
Use cy.get() with meaningful selectors
Use assertions like .should('be.visible')
Avoid hardcoded waits; rely on Cypress automatic waits
Write clear test descriptions
Automated Solution
Cypress
describe('Responsive layout test with cy.viewport()', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io')
  })

  it('shows mobile menu button on small screen', () => {
    cy.viewport(320, 480)
    cy.get('.mobile-menu-button').should('be.visible')
  })

  it('shows navigation bar on tablet screen', () => {
    cy.viewport(768, 1024)
    cy.get('.navigation-bar').should('be.visible')
  })

  it('shows full navigation menu on desktop screen', () => {
    cy.viewport(1280, 800)
    cy.get('.full-navigation-menu').should('be.visible')
  })
})

This test suite uses cy.viewport() to simulate different screen sizes: mobile, tablet, and desktop.

Each test visits the website fresh to avoid state carryover.

Selectors like .mobile-menu-button, .navigation-bar, and .full-navigation-menu represent elements expected to appear at each screen size.

Assertions use .should('be.visible') to confirm the correct layout is shown.

Cypress automatically waits for elements, so no manual waits are needed.

Common Mistakes - 3 Pitfalls
Using fixed waits like cy.wait(500) instead of relying on Cypress automatic waits
{'mistake': "Using incorrect or overly generic selectors like 'button' instead of specific classes or IDs", 'why_bad': 'Generic selectors can match multiple elements and cause flaky tests.', 'correct_approach': 'Use unique, meaningful selectors such as classes or data attributes.'}
Not resetting viewport between tests causing state leakage
Bonus Challenge

Now add data-driven testing to check the layout on these three screen sizes in a single test using an array of viewport sizes.

Show Hint