0
0
Cypresstesting~5 mins

cy.viewport() for screen sizes in Cypress

Choose your learning style9 modes available
Introduction

We use cy.viewport() to test how a website looks and works on different screen sizes. This helps make sure the site works well on phones, tablets, and computers.

You want to check if a button is visible on a small phone screen.
You need to test if a menu changes correctly on a tablet size.
You want to verify that images resize properly on a desktop screen.
You want to make sure text is readable on different devices.
You want to test responsive layouts without changing your actual device.
Syntax
Cypress
cy.viewport(width, height)
// or
cy.viewport(presetName)

// width and height are numbers (pixels)
// presetName is a string like 'iphone-6', 'ipad-2', 'macbook-15'

You can use exact width and height in pixels.

Or use preset device names for common screen sizes.

Examples
Set viewport to 320 pixels wide and 480 pixels tall (small phone size).
Cypress
cy.viewport(320, 480)
Set viewport to the size of an iPhone 6 using a preset name.
Cypress
cy.viewport('iphone-6')
Set viewport to a 15-inch MacBook screen size preset.
Cypress
cy.viewport('macbook-15')
Sample Program

This test sets the screen size to iPhone 6 and checks if the mobile menu button is visible. Then it sets a desktop size and checks if the full desktop menu is visible.

Cypress
describe('Test responsive layout', () => {
  it('shows mobile menu on small screen', () => {
    cy.viewport('iphone-6')
    cy.visit('https://example.cypress.io')
    cy.get('.mobile-menu-button').should('be.visible')
  })

  it('shows full menu on desktop', () => {
    cy.viewport(1280, 720)
    cy.visit('https://example.cypress.io')
    cy.get('.desktop-menu').should('be.visible')
  })
})
OutputSuccess
Important Notes

Always set viewport before visiting the page to simulate the device correctly.

Use cy.viewport() to catch layout bugs early.

Combine with screenshots to see visual differences.

Summary

cy.viewport() changes the screen size for your test.

You can use pixel sizes or device presets.

This helps test responsive design easily.