sodcalculator

10 Tech How-To

How to Test a Mobile Web App with Cypress

Guide 10-43468 · Updated · Step by step

This guide walks you through setting up and running Cypress tests specifically for a mobile web app, covering viewport emulation, touch events, and responsive design checks. By the end, you’ll have a repeatable test suite that mimics how real users interact with your app on phones and tablets.

What You’ll Need

  • Node.js (version 18 or later) installed on your machine
  • A code editor (VS Code, Sublime, etc.)
  • Basic familiarity with JavaScript and the command line
  • An existing mobile web app to test (or a sample app to practice on)

Step-by-Step

  1. Install Cypress
    Open your terminal, navigate to your project folder, and run npm init -y to create a package.json if you don’t have one. Then install Cypress as a dev dependency: npm install cypress --save-dev. This will download the Cypress binary and set up the necessary files.
  2. Open Cypress for the first time
    Run npx cypress open. The first launch will create a cypress folder with subfolders: e2e, fixtures, and support. It also creates a cypress.config.js file at your project root. Close the Cypress window for now.
  3. Configure the base URL
    Open cypress.config.js and set the baseUrl to your mobile web app’s URL (e.g., https://m.example.com). This allows you to use relative paths in your tests. Save the file.
  4. Set up viewport presets
    In the cypress/support folder, create a new file called commands.js (if it doesn’t exist) and add custom commands for common mobile viewports. For example:

    Cypress.Commands.add('setMobileViewport', () => {
      cy.viewport(375, 667); // iPhone SE size
    });
    Cypress.Commands.add('setTabletViewport', () => {
      cy.viewport(768, 1024); // iPad size
    });

    This makes it easy to switch between devices in your tests.

  5. Write your first mobile test
    Navigate to cypress/e2e and create a test file, e.g., mobile-home.spec.js. Start with a simple test that sets the viewport and visits your app:

    describe('Mobile Home Page', () => {
      it('loads correctly on a phone', () => {
        cy.setMobileViewport();
        cy.visit('/');
        cy.get('h1').should('be.visible');
      });
    });

    Use cy.setMobileViewport() to emulate a phone screen.

  6. Test touch interactions
    Cypress supports touch events via the cy.trigger() method. For example, to simulate a swipe on a carousel:

    cy.get('.carousel')
      .trigger('touchstart', { touches: [{ clientX: 300, clientY: 400 }] })
      .trigger('touchmove', { touches: [{ clientX: 100, clientY: 400 }] })
      .trigger('touchend');

    This mimics a left swipe. You can also use cy.tap() if you have the cypress-plugin-tap installed, but the trigger method is built-in.

  7. Verify responsive layout
    Use assertions to check that elements are visible and positioned correctly on mobile. For example, check that a menu button is visible but the full nav is hidden:

    cy.get('.hamburger').should('be.visible');
    cy.get('.nav-links').should('not.be.visible');

    Then tap the hamburger and assert the nav appears.

  8. Run tests in headless mode
    For CI or quick checks, run npx cypress run. This executes all tests in headless mode. To run a specific file, add --spec flag: npx cypress run --spec "cypress/e2e/mobile-home.spec.js".
  9. Use device emulation presets
    Cypress has built-in device presets. Instead of custom commands, you can use cy.viewport('iphone-6') or cy.viewport('ipad-2'). Check the Cypress docs for the full list of presets.
  10. Add a test for touch-only features
    If your app has features that only appear on touch devices, test them. For example, test that a long-press triggers a context menu:

    cy.get('.item')
      .trigger('pointerdown', { button: 0, pointerType: 'touch' })
      .wait(600)
      .trigger('pointerup');

    Adjust the wait time to match your app’s long-press threshold.

Common Mistakes

  • Forgetting to set viewport before visiting – If you call cy.visit() before setting the viewport, the page loads in desktop mode and may not trigger mobile-specific JavaScript. Always set the viewport first.
  • Using desktop-only selectors – Mobile layouts often hide or replace elements. Make sure your selectors target elements that exist in the mobile DOM.
  • Ignoring touch events – Many mobile apps rely on touch events (touchstart, touchmove). Cypress defaults to mouse events, so you must explicitly trigger touch events for interactions like swiping.
  • Not waiting for network requests – Mobile networks are slower. Use cy.intercept() and cy.wait() to handle API calls, or use cy.visit(url, { timeout: 10000 }) to increase the timeout.
  • Assuming exact pixel dimensions – Different devices have different pixel ratios. Use relative selectors and CSS assertions rather than hard-coded coordinates.

Tips

  • Use cy.viewport() in a beforeEach hook to ensure every test runs with the same mobile viewport.
  • Take screenshots on failure: Cypress automatically captures screenshots when a test fails. You can also manually capture them with cy.screenshot() for visual inspection.
  • Test on multiple viewports by iterating over an array of sizes in a single test, or use parameterized tests.
  • Use the Cypress Chrome DevTools integration to debug: open the test runner, click on a command, and inspect the DOM state at that moment.
  • For real device testing, consider using Cypress with a cloud service like BrowserStack, but local emulation is usually sufficient for most bugs.

Troubleshooting

  • Tests pass on desktop but fail on mobile – Likely due to viewport size. Double-check that you set the viewport before visiting the page. Also, inspect the DOM using cy.debug() or cy.pause() to see what elements are actually present.
  • Touch events not triggering – Ensure you’re using the correct event names. Some apps listen for pointerdown instead of touchstart. Try both, or use cy.trigger('pointerdown', { pointerType: 'touch' }).
  • Cypress can’t find an element that is visible on a real phone – The element might be inside a shadow DOM or an iframe. Use cy.get('selector', { includeShadowDom: true }) or cy.iframe() to access it.
  • Tests are flaky on slow networks – Increase timeouts globally in cypress.config.js with defaultCommandTimeout: 10000. Also, use cy.intercept() to stub network requests and make tests deterministic.
  • Viewport preset not working – Check that you’re using a valid preset name. Refer to the Cypress documentation for the exact list. If you need a custom size, use cy.viewport(width, height).

Frequently Asked Questions

Can Cypress test on actual mobile devices?

Cypress runs in a browser on your computer, so it emulates device sizes but not actual hardware. For real device testing, you need a cloud service or a separate setup like Appium. However, emulation is sufficient for most layout and interaction bugs.

How do I simulate a slow network in Cypress?

Use cy.intercept() to delay responses. For example, cy.intercept('*', (req) => { req.continue((res) => { res.setDelay(1000); }); }); adds a 1-second delay to all responses.

Does Cypress support multi-touch gestures like pinch?

Not natively. You can simulate basic touch events with cy.trigger(), but complex gestures like pinch require custom JavaScript or a plugin. For most web apps, single-touch swipes and taps are sufficient.

Why do my tests fail only in headless mode?

Headless mode may have different default viewport or screen size. Set the viewport explicitly in your tests, and also ensure your app doesn’t rely on browser extensions or features that are disabled in headless mode.

Can I use Cypress to test a responsive design on multiple breakpoints in one run?

Yes. Write a loop that iterates over an array of viewport sizes and runs the same assertions for each. For example, ['iphone-6', 'ipad-2', 'macbook-13'].forEach((size) => { it(...) }).

How do I handle file uploads on mobile emulation?

Use cy.get('input[type=file]').attachFile('path/to/file') with the cypress-file-upload plugin. This works regardless of viewport size.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →