Cypress: Viewport


The viewport of a web page is the area of the web page visible to the user. That the web page and the parts of it visible to the user at once are not always the same is something which has become more important ever since the same web page can be visited by devices with very different screen sizes, like desktop computers, tablets, mobile phone, …

For Cypress the viewport is what you see in the Cypress runner GUI.

Let’s assume we have the following web page:

<html>
  <body>
    <p>
      This is a test page.
    </p>
    <input type="text" id="test-input" value="" />  
  </body>
</html>

And the following Cypress test:

/// <reference types="cypress" />
import { recurse } from '../../src'

describe(
  'test',
  { defaultCommandTimeout: 2500 },
  () => {
    it('Test 1', () => {
      cy.visit('cypress/integration/test.html')
      const text = 'Test 1 input!'
      cy.get('#test-input').should('be.visible')
    })

    it('Test 2', () => {
        cy.visit('cypress/integration/test.html')
        const text = 'Test 1 input!'
        cy.get('#test-input').type(text).should('have.value', text)
    })
  },
)

If we run the test, we get the following output in the Cypress runner:

Let’s change the viewport height and width:

/// <reference types="cypress" />
import { recurse } from '../../src'

describe(
  'test',
  {  viewportHeight: 300, viewportWidth: 500, defaultCommandTimeout: 2500 },
  () => {
    it('Test 1', () => {
      cy.visit('cypress/integration/test.html', {
        onBeforeLoad(win){
            Object.defineProperty(win.navigator, 'language', { value: 'fr-FR' })
        }})
      const text = 'Test 1 input!'
      cy.get('#test-input').should('be.visible')
    })

    it('Test 2', () => {
        cy.visit('cypress/integration/test.html', {
            onBeforeLoad(win){
                Object.defineProperty(win.navigator, 'language', { value: 'fr-FR' })
            }})
        const text = 'Test 1 input!'
        cy.get('#test-input').type(text).should('have.value', text)
    })
  },
)

The result will be a smaller viewport defined by the viewport height and width we just defined: