TutorialsLast Updated Nov 4, 20268 min read

Viewport testing with Cypress

Waweru Mwaura

Software Engineer

Ensuring that an application renders properly in any browser size is important for user experience but tricky to get right. With users accessing your application on devices that have a wide range of screen sizes and aspect ratios, it’s difficult to guarantee that your application will look and function as intended for every user.

Viewport testing ensures that web applications work as intended in different device screen sizes. In this tutorial, you will learn the importance of using Cypress to test viewports for browser and mobile versions of an application. You’ll learn how to add viewport tests to an application, and then you’ll integrate CircleCI as part of the CI/CD process to automate your viewport tests, giving you continuous feedback on your application’s responsiveness and functionality across various devices.

Prerequisites

To follow along with this tutorial, you will need the following:

Installing the sample project’s dependencies also installs Cypress 16.

Setting up the sample application

To get started quickly, use the sample application built for this tutorial. Follow these steps to clone and try out the application.

First, clone the application from the GitHub repository:

git clone https://github.com/CIRCLECI-GWP/viewport-testing-with-cypress.git

Then, cd into the cloned directory:

cd viewport-testing-with-cypress

Next, install the dependencies needed for this tutorial. Execute this command:

npm install

Finally, run npm start and visit the application in your browser at localhost:9000.

The sample travel agency site open in Chrome at localhost:9000, with the HOME, FEATURES, CONTACT, and LOG IN navigation links and the Book With Us heading

What are viewports?

A viewport is the area of a webpage that a user can see on their display. This varies depending on the type of device or display, as well as the window on which a webpage is being displayed.

Most web traffic is generated through mobile devices, so most web applications are optimizing interfaces for these devices. Testing viewports ensures that no matter what device or screen size is in use, the functionality is similar if not better while still ensuring that the performance is optimal.

Here’s an illustration of the different steps a user might take when using the browser and mobile viewports:

A diagram of a user's two paths: the browser viewport shows a full navigation bar and full-sized images, and the mobile viewport shows dropdown navigation and smaller images

This tutorial uses Cypress for viewport testing because it lets you write tests quickly and run them in a real browser.

Cypress also allows you to control the dimensions of the viewport and therefore test for multiple viewports at once. It is important to know that for Cypress to achieve this, it just sets the browser’s width and height to the device resolution that is under test.

Cypress configuration

Open a new terminal while in the viewport-testing-with-cypress directory. It is important that you keep open the terminal window that is running your application from the npm start command.

The project’s Cypress settings live in cypress.config.js in the root directory. It sets baseUrl to the address of the running application, so the tests can visit / instead of the full URL:

const { defineConfig } = require("cypress")

module.exports = defineConfig({
  e2e: {
    baseUrl: "http://localhost:9000",
  },
})

In your new window, start Cypress. Run:

npx cypress open

Cypress opens the Cypress app. Select E2E Testing, choose Chrome as the browser, and click Start E2E Testing in Chrome. In the list of specs, click travel.cy.js (in this case, there is only one). Cypress runs the tests in Chrome and shows the test output.

The Cypress app running travel.cy.js in Chrome, with all five tests passing, including the desktop viewport and mobile viewport groups, and the app previewed at 375x667 with its menu open

The first two test cases ensure the webpage loads without issues; these tests pass successfully. The tests live in travel.cy.js in the cypress/e2e folder for this tutorial. They look like this:

/// <reference types="cypress" />

describe("Cypress Viewport Tests Suite", () => {
    beforeEach(() => {
        cy.visit("/")
        // Each test starts on a fresh page, so visit the home page first
    })

    it("should be able to load the page", () => {
        cy.title().should("eq", "Travel Agency")
    })

    it("should load the features page", () => {
        cy.get("a[id=featuresBtn]").click()
        cy.contains("Your favorite places are waiting! Let us help bring your dreams to life")
    })

})

Cypress isolates each test: it clears the page before every test. The beforeEach() hook visits the site’s URL before each test, and the first test checks the page title to make sure the page loaded properly. In the second test, Cypress clicks the features button and checks whether the resulting page contains “Your favorite places are waiting! Let us help bring your dreams to life”.

The rest of the tests are broken into two groups: those for the desktop viewport and those for the mobile viewport.

Cypress uses the Mocha framework and Chai assertion library to help with the organization of tests. One of the extended features is context(), which the example uses to differentiate the viewports for different devices.

The next code snippet lives in the test suite of the travel.cy.js file, and handles the desktop viewport tests.

context("desktop viewport", () => {
    beforeEach(() => {
        cy.viewport(1536, 960)
        // Runs the tests in this context for the resolution defined
    })

    it("displays the whole navigation bar", () => {
        cy.get(".navbar").should("be.visible")
        cy.get("div[id=menu-btn]").should("not.be.visible")
    })
})

This is the test for the desktop resolution, where you ensure that the entire navigation bar is displayed. It uses the cy.get() command to access the elements and selectors. It then uses the should() assertion to ensure that the entire navigation bar is visible. Because all the links to pages can fit within this large viewport, the next line ensures that we don’t show the hamburger menu.

The next test verifies mobile. This test makes sure that the toggle button is visible and you can access link elements to other pages by clicking it.

context("mobile viewport", () => {
    beforeEach(() => {
        cy.viewport("iphone-6")
        // Runs the tests in this context for the resolution defined
    })

    it("displays the hamburger menu", () => {
        cy.get("div[id=menu-btn]").should("be.visible")
    })

    it("clicks the toggle button", () => {
        cy.get("div[id=menu-btn]").should("be.visible").click()
        cy.get(".content").should("be.visible")
    })
})

This code snippet shows the different ways to pass a viewport configuration to your Cypress tests. We can do it either in terms of the screen resolution or common mobile device names like the iphone-6. For more information on the arguments to pass to the method, you can check the Cypress documentation on viewport arguments.

Configuring CircleCI

CircleCI is a CI/CD platform that automates test runs. The project contains a .circleci folder in the root directory with a config.yml file that holds the configuration. This project’s config.yml is straightforward:

version: 2.1
orbs:
  cypress: cypress-io/cypress@6.1.0
workflows:
  build:
    jobs:
      - cypress/run:
          install-browsers: true
          start-command: npm start
          cypress-command: npx wait-on@latest http://localhost:9000 && npx cypress run --browser chrome

You are using CircleCI’s Cypress orb, which is a pre-built configuration that installs and configures dependencies, caches them on CircleCI, and does all the heavy lifting for your configuration. The cypress/run job installs Chrome (install-browsers), starts the application in the background (start-command), and then waits for localhost:9000 to respond before running the tests in Chrome (cypress-command).

To run the test for this project in your own CircleCI account, push your changes to a new remote repository on GitHub. You can do this by creating an empty repository on GitHub and then running this in the root of the example project:

git remote set-url origin <URL-OF-YOUR-NEW-REPO>

Next, push the example project to your GitHub with:

git push

Log in to your CircleCI account and select the organization.

The Cypress orb is a partner orb, and CircleCI treats partner orbs as uncertified, so the organization has to allow uncertified orbs before a pipeline can use it. An organization admin has to turn this on. In the sidebar, select Org to open the organization settings. In a shorter browser window, Org is under More. Select Security, and under Orb Security Settings, turn on Allow uncertified public orbs. Without this setting, the pipeline fails before any job runs, with the error “Orb cypress-io/cypress@6.1.0 not loaded.”

The CircleCI organization settings with Security selected, showing the Orb Security Settings section with Allow certified public orbs, Allow uncertified public orbs, and Allow private orbs turned on

Next, set up the project. The steps depend on the organization’s type, which its URL in the web app shows: /circleci/ for organizations connected through the CircleCI GitHub App, and /github/ or /gh/ for organizations connected through the GitHub OAuth app.

  • Organizations connected through the CircleCI GitHub App: on the Home page, click Create project and follow the prompts: name the project, set up a pipeline, and choose the repository. If CircleCI prompts for a GitHub connection, install the CircleCI GitHub App and give it access to the repository. Keep the default trigger, which runs the pipeline on every commit, and use the existing .circleci/config.yml file as the config source. Review your choices and finish creating the project. Then push a small commit that doesn’t functionally change anything, like changing the name of a test, to trigger your first pipeline run.
  • Organizations connected through the GitHub OAuth app, which CircleCI creates when a user signs in with a GitHub account: select Projects in the sidebar, find the repository, and click Set up. Choose Fastest, which uses the .circleci/config.yml already in the repository, enter main as the branch, and click Set Up Project. CircleCI starts the first pipeline run right away.

In a GitHub OAuth app organization, the Select your config.yml file dialog in CircleCI, with the Fastest option selected for the viewport-testing-with-cypress repository, main entered as the branch, a message that .circleci/config.yml was found on this branch, and the Set Up Project button

When the pipeline finishes, open the cypress/run job and expand the Run Cypress step to see the test results:

The cypress/run job in CircleCI with the Run Cypress step expanded, showing the wait-on and cypress run command, all five tests in the Cypress Viewport Tests Suite passing, 5 passing, and a results table with 5 tests and 0 failing

Voila! Just like that, you have set up your project and integrated CircleCI into it. Now, any time you update your project code, CircleCI will automatically trigger your Cypress tests, giving you the feedback you need to move quickly and confidently.

Conclusion

In this tutorial, you’ve learned how to use Cypress to test viewports. You then used the Cypress orb to integrate CircleCI into your development cycle and automate your test runs.

Testing viewports is important to ensure a great user experience no matter the screen sizes or orientation of the contents of a web application. I hope you enjoyed reading this tutorial as much as I did creating it. Until the next one, keep learning!