Cypress Viewport Command

Profile picture for user devraj

Cypress Viewport command controls the orientation and size of the screen of your application. Using this command, you can set the size of desktop, mobile, and tablet devices. This command yields null.

Cypress Default Viewport

By default, without viewport command, Cypress sets the width to 1000px and height to 660px.  You can check the viewport value using below code:

cy.log('Width:' + Cypress.config('viewportWidth'))
cy.log('Height:' + Cypress.config('viewportHeight'))

If you have added value to cypress.json, it will return value from the JSON file.

cypress.json viewport

You can set the dimension globally by adding the value viewportWidth and viewportHeight in your configuration file.

{
  "baseUrl": "https://www.programsbuzz.com",
  "viewportHeight": 1080,
  "viewportWidth": 1920,
}

Cypress Autoscaling

Cypress supports auto-scaling by default. If your screen is not large enough to display all of the current dimension's pixels, Cypress will scale and center your application within the Cypress runner to accommodate. It will not impact the behavior of your application.

Syntax

Here is the syntax:

cy.viewport(width, height)
cy.viewport(preset, orientation)
cy.viewport(width, height, options)
cy.viewport(preset, orientation, options)
  1. width: Accept non-negative finite number to set the width in pixels.
  2. height: Accept non-negative finite numbers to set the width in pixels.
  3. preset: It accepts preset string values for devices like iphone-6, iphone-x, macbook-11, and macbook-13. The complete preset table is given below.
  4. orientation: The default value is portrait. Set the orientation to landscape by giving landscape value.
  5. options: Only accepted object is the log.

Rules

  • cy.viewport() requires being chained off of cy and cannot be chained further.
  • cy.viewport() cannot have any assertions chained.
  • cy.viewport() cannot time out.

Cypress Viewport Presets and Sizes

Presetwidthheight
ipad-27681024
ipad-mini7681024
iphone-3320480
iphone-4320480
iphone-5320568
iphone-6375667
iphone-6+414736
iphone-7375667
iphone-8375667
iphone-x375812
iphone-xr414896
iphone-se2375667
macbook-111366768
macbook-131280800
macbook-151440900
macbook-161536960
samsung-note9414846
samsung-s10360760

Cypress Viewport Example 

You can set viewport by giving width and height or by giving presets.

Cypress Set Viewport Width and Height

cy.viewport(375, 667)

Cypress Set Viewport Using Presets and Orientation

cy.viewport('iphone-5', 'landscape')