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
- Install Cypress
Open your terminal, navigate to your project folder, and runnpm init -yto 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. - Open Cypress for the first time
Runnpx cypress open. The first launch will create acypressfolder with subfolders:e2e,fixtures, andsupport. It also creates acypress.config.jsfile at your project root. Close the Cypress window for now. - Configure the base URL
Opencypress.config.jsand set thebaseUrlto 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. - Set up viewport presets
In thecypress/supportfolder, create a new file calledcommands.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.
- Write your first mobile test
Navigate tocypress/e2eand 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. - Test touch interactions
Cypress supports touch events via thecy.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 thecypress-plugin-tapinstalled, but the trigger method is built-in. - 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.
- Run tests in headless mode
For CI or quick checks, runnpx cypress run. This executes all tests in headless mode. To run a specific file, add--specflag:npx cypress run --spec "cypress/e2e/mobile-home.spec.js". - Use device emulation presets
Cypress has built-in device presets. Instead of custom commands, you can usecy.viewport('iphone-6')orcy.viewport('ipad-2'). Check the Cypress docs for the full list of presets. - 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()andcy.wait()to handle API calls, or usecy.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 abeforeEachhook 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()orcy.pause()to see what elements are actually present. - Touch events not triggering – Ensure you’re using the correct event names. Some apps listen for
pointerdowninstead oftouchstart. Try both, or usecy.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 })orcy.iframe()to access it. - Tests are flaky on slow networks – Increase timeouts globally in
cypress.config.jswithdefaultCommandTimeout: 10000. Also, usecy.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
- Set a Google Play Budget & Stop Accidental Purchases
- Destiny 2 Error Code Anteater: Fixes & Causes
- View Android Photos on Chromebook: Step-by-Step
- Fix Windows Could Not Prepare the Computer to Boot
- Windows 11 Security Settings: Best Config Guide
- Block Ads Network Wide at the Router Level