Cypress Dynamically Test Multiple Viewports

Cypress Dynamically Test Multiple Viewports

So we know what a viewport in cypress is. 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.

Set the viewport with the width or presets and orientation to start testing it in the precisely specified environment.

Either set like this in the cypress.json file:

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

Or like this in the test step:

cy.viewport(width, height)

Or even like this with preset and orientation:

cy.viewport('iphone-5', 'landscape')
  • So what if there is a way to test viewport dynamically.
  • In this article, we will be seeing how we can test in cypress using viewport dynamically in all preset and width environments without hardcoding.
  • We will be using our traditional programsbuzz  site for this.
const sizes = ['iphone-6', 'ipad-2', 'iphone-x', 'samsung-s10', [1920, 1080]]

describe('Logo', () => {
  sizes.forEach((size) => {

    it(`Should display logo on ${size} screen`, () => {
      if (Cypress._.isArray(size)) {
        cy.viewport(size[0], size[1])
      } else {
        cy.viewport(size)
      }

      cy.visit('https://www.programsbuzz.com/')
      cy.get('.site-branding-logo').should('be.visible')
    })
  })
})
  • So the presets are stored in an array; also, there is a custom resolution width and height in the collection.
  • Using foreach, we are iterating the array. If the size variable we created is an array, it will execute the following two conditions.
  • Which sets the viewport based on the size index.
  • So we are using a simple assertion to check whether the logo of the programbuzz site is visible.

  • We can see that it is visible on the different viewports from the array.
  • We can add more presets too into this array which will test in each of the cypress viewports dynamically using this method.
Tags
Standard (Image)