0
0
CypressHow-ToBeginner ยท 3 min read

How to Test Responsive Design with Cypress: Simple Guide

To test responsive design in Cypress, use the cy.viewport() command to set the screen size to different device dimensions. Then, write assertions to check if elements appear or behave correctly at each size.
๐Ÿ“

Syntax

The cy.viewport() command sets the browser window size to simulate different devices or screen sizes. It accepts width and height in pixels or device names.

  • cy.viewport(width, height): Set custom width and height in pixels.
  • cy.viewport(deviceName): Use predefined device sizes like 'iphone-6', 'ipad-2', etc.

Use this before your assertions to test how your app looks on different screens.

javascript
cy.viewport(375, 667) // iPhone 6 size
cy.viewport('ipad-2') // predefined device size
๐Ÿ’ป

Example

This example tests a responsive navigation menu that should be visible on desktop but hidden on mobile.

javascript
describe('Responsive Design Test', () => {
  it('shows menu on desktop and hides on mobile', () => {
    // Desktop viewport
    cy.viewport(1024, 768)
    cy.visit('https://example.com')
    cy.get('#nav-menu').should('be.visible')

    // Mobile viewport
    cy.viewport('iphone-6')
    cy.visit('https://example.com')
    cy.get('#nav-menu').should('not.be.visible')
  })
})
Output
Test passes if #nav-menu is visible on desktop and hidden on mobile.
โš ๏ธ

Common Pitfalls

Common mistakes when testing responsive design with Cypress include:

  • Not setting the viewport size before visiting the page, which can cause inconsistent results.
  • Using fixed pixel assertions that break on different screen sizes.
  • Forgetting to wait for layout changes or animations after resizing.

Always set cy.viewport() before cy.visit() if the page loads differently based on screen size.

javascript
/* Wrong way: viewport set after visit */
cy.visit('https://example.com')
cy.viewport('iphone-6')

/* Right way: viewport set before visit */
cy.viewport('iphone-6')
cy.visit('https://example.com')
๐Ÿ“Š

Quick Reference

CommandDescriptionExample
cy.viewport(width, height)Set custom screen sizecy.viewport(800, 600)
cy.viewport(deviceName)Set predefined device sizecy.viewport('iphone-x')
cy.get(selector).should('be.visible')Assert element visibilitycy.get('#menu').should('be.visible')
cy.get(selector).should('not.be.visible')Assert element hiddency.get('#menu').should('not.be.visible')
โœ…

Key Takeaways

Use cy.viewport() to simulate different screen sizes for responsive testing.
Set viewport before visiting the page to ensure correct layout loading.
Write assertions to check element visibility or layout changes at each size.
Avoid fixed pixel assertions that do not adapt to screen size changes.
Wait for any animations or layout shifts after resizing before asserting.