Change a viewport width and height in a cypress test

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet

Long time ago, frontend developers (or as we called them back then - webmasters) could get away with supporting only one or two resolutions.

Those days are long gone.

In this lesson we're going to learn how to change a viewport width and height in a cypress test in order to ensure that our app works as intended on a given resolution.

Tomasz Łakomy: [00:00] We have a bunch of Cypress tests that are testing our UI. If we take a look, we are going to see that they are testing only one very specific resolution. That resolution is this, set over here, which is 1000 x 660. This is a default one, but of course we can change it with Cypress. There are two ways to do that.

[00:15] First up, we can go to cypress.json in order to change the default resolution. If I go over here to cypress.json, which is Cypress's configuration file, I can go ahead and change the default viewportWidth and viewportHeight. Let me change it to full HD because why not?

[00:30] I'm going to save that and start the test again. Now all of our tests are using the updated resolution of full HD.

[00:36] That's awesome, but it is not perfect because we just ended up overwriting one default value with another default value. We would like to be able to also change the viewport width and height on a test-to-test basis.

[00:44] For instance, imagine that we would like to run this entire suite of tests on a mobile device. In order to do that, we're going to use the cy.viewport() command. This command allows us to change the viewport. I'm going to put it in beforeEach() command because I would like this viewport to be updated before every single test.

[00:59] For instance, here, I can set the width to 500 and a height to 700. If I save that, we're going to run our tests on our mobile device.

[01:07] One also thing about this viewport command is that we don't have to specify the width and height as a number. Instead, we can use a predefined value of for instance, iPhone-5 and if I save that, we are going to run those tests on a resolution of iPhone 5. It also works with other devices such as Samsung Galaxy 10. If I save that, we're going to run those tests on a Samsung Galaxy 10.

[01:26] We are not only limited to mobile phones because I can also paste in an ipad-2. If I save that, we're going to run those tests on an iPad.

[01:33] One thing that is important when it comes to tablets is to be able to support both portrait and landscape mode. The default one is portrait, but if I change the orientation to landscape by providing a second argument to this viewport function, if I save that we're going to run those tests on an iPad 2 in a landscape mode.