skip to Main Content

I’m writing a test suite for an application that will predominantly have users on mobile devices, but is likely to have some admin users on laptops. For the majority of tests, I want a mobile orientation, so have the following code in my cypress.config.js file;

viewportHeight: 1280,
viewportWidth: 720,

… Fairly straight forward. All my tests for laptop users will be contained in a separate folder however, so I was wondering if there’s a simple way in Cypress (without writing it in every test case individually) to make it use a different Viewport size if the folder path of the tests is a specific path? I can’t seem to find a neat way to do this.

There won’t be any overlap in testing on the screens that mobile users, and laptop users will need to use. So I’m not trying to test every screen on 2 different orientations, this will be one folder of tests that uses a different Viewport Height/Width than every other folder.

Thanks in advance!

2

Answers


  1. You can use Cypress’ global beforeEach() in the supportFile to ensure certain code runs before every test. Coupling that with Cypress.spec, we can check the filepath of the current spec being run, and determine what the viewport should be.

    // In the support file, most likely cypress/support/e2e.js
    
    beforeEach(() => {
      const isLaptopUser = Cypress.spec.relative.includes('/laptop');
      cy.viewport(isLaptopUser ? 1440 : 720, isLaptopUser ? 2560 : 1280)
    });
    

    Note: cy.viewport can accept multiple signatures, the one above uses width, height.

    Login or Signup to reply.
  2. The viewport can be configured at the top of the spec. If you do it this way you have more flexibility than using a complicated algorithm set at the global level.

    For example you can make temporary changes right in the spec, and you can move the specs around as required without bother.

    
    describe('tests at laptop view', {viewportHeight: 900, viewportWidth: 1440,}, () => {
    
      it('test 1', () => {
        ...
      })
    
      it('test 2', () => {
        ...
      })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search