Cypress Headless Chrome Viewport Setup Guide
In this article
Configuring Cypress with custom viewport dimensions in headless Chrome allows tests to simulate specific screen sizes, ensuring responsive design behaves correctly across devices. This setup is essential for developers who need to validate UI elements under consistent conditions without launching a visible browser. You can define viewport sizes globally or per test, giving flexibility for mobile, tablet, and desktop views. This guide walks through setup, configuration, and best practices for reliable, repeatable testing.
What You'll Need
- Node.js installed (version 14 or higher recommended)
- A project initialized with npm or yarn
- Cypress installed as a dev dependency
- Google Chrome or Chromium browser installed (for headless execution)
- Basic understanding of JavaScript and Cypress syntax
Step-by-Step
- Install Cypress if not already present by running
npm install cypress --save-devin your project root. This adds Cypress to yourpackage.jsonunderdevDependencies. - Create or edit the
cypress.config.jsfile in your project directory. If using an older version of Cypress, this may becypress.json. For Cypress 10+, use the JavaScript configuration format. - In
cypress.config.js, define viewport dimensions globally using theviewportWidthandviewportHeightoptions. Example:
This sets the default viewport for all tests.module.exports = { viewportWidth: 1366, viewportHeight: 768, }; - To run tests in headless Chrome, use the command
npx cypress run --browser chrome --headless. This executes tests without a GUI, using Chrome's headless mode with the defined viewport. - Override viewport settings in individual test files using
cy.viewport(). Insert this command inside a test or hook:
This is useful for testing mobile responsiveness within specificcy.viewport(375, 667); // Simulates iPhone 6/7/8it()blocks. - Use predefined device presets by passing a string to
cy.viewport():
Supported presets include 'macbook-15', 'ipad-2', 'iphone-x', and others. Refer to Cypress documentation for the full list.cy.viewport('iphone-6'); - For dynamic viewport changes within a single test, call
cy.viewport()multiple times. Example:
This verifies layout changes at different breakpoints.it('tests responsiveness', () => { cy.viewport(1200, 800); cy.get('.navbar').should('be.visible'); cy.viewport(320, 480); cy.get('.navbar-toggle').should('be.visible'); }); - Ensure Chrome is detected by Cypress by verifying browser list via
npx cypress info. This command shows available browsers. If Chrome isn't listed, check installation or use--browser chromiumif Chromium is installed. - Store custom viewport sizes in support files or constants for reuse. Create a
constants.jsfile:
Then import and use in tests:export const VIEWPORTS = { mobile: [375, 667], tablet: [768, 1024], desktop: [1920, 1080] };cy.viewport(...VIEWPORTS.mobile);. - Validate viewport settings by logging dimensions in a test:
This confirms the viewport was applied correctly.cy.window().then((win) => { expect(win.innerWidth).to.equal(375); expect(win.innerHeight).to.equal(667); });
Common Mistakes
- Setting viewport dimensions in
cypress.jsonbut not restarting the test runner — changes require a restart to take effect. - Using
cy.viewport()outside of a test orbeforeEachhook, which causes errors. It must be called within a runnable context. - Assuming headless mode uses the same default viewport as headed mode — always define dimensions explicitly to avoid inconsistencies.
- Forgetting to specify
--browser chromein the run command, causing Cypress to default to Electron with different rendering behavior. - Overriding global settings incorrectly — per-test
cy.viewport()calls take precedence, so ensure expectations align with the active configuration.
Tips
- Use
cy.viewport()inbeforeEach()to standardize dimensions across multiple tests in a suite. - Combine viewport testing with
cy.screenshot()to visually verify layout changes at different sizes. - Define multiple test configurations using
--configflag:npx cypress run --config viewportWidth=414,viewportHeight=896. - Test critical breakpoints used in your CSS media queries to ensure UI transitions work as intended.
- Run headless tests in CI/CD pipelines with consistent viewport settings to avoid flaky layout-related failures.
Troubleshooting
If viewport settings don't apply, first confirm that the config file is correctly named and located in the project root. For cypress.config.js, ensure it exports an object with valid options. If using TypeScript, verify cypress.config.ts is transpiled or configured properly.
If Chrome isn't launching in headless mode, check the exact command syntax. Use --browser chrome only if Chrome is installed and detected. On CI environments, Chromium is often preferred; use --browser chromium and install it via package manager if needed.
When cy.viewport() throws an error, ensure it's called within a test block or supported hook (beforeEach, before). Calling it in describe() directly will fail.
If screenshots show unexpected scaling, verify no CSS zoom or transform styles are applied globally. Also, ensure viewport meta tags in your app don't interfere with test rendering.
For inconsistent behavior between local and CI runs, standardize Cypress and Chrome versions across environments using engines field in package.json or Docker images.
Frequently Asked Questions
Can I set different viewports for different test files?
Yes. Usecy.viewport() at the beginning of each test file or within specific describe blocks to customize dimensions per suite.
Does headless Chrome support all viewport sizes?
Yes. Headless Chrome supports any viewport dimensions, though extremely small or large values may affect rendering accuracy.How do I disable viewport scaling in Chrome?
Cypress automatically manages viewport without scaling. Avoid settingviewport meta tags that force scaling in your app during testing.
Can I test landscape and portrait modes?
Yes. Swap width and height values usingcy.viewport(667, 375) for landscape iPhone, for example.
Is viewport configuration necessary for headless tests?
Yes. Without explicit settings, Cypress uses default dimensions that may not match your design requirements.Can I use environment variables for viewport sizes?
Yes. UseCypress.config() with environment variables in cypress.config.js to dynamically set dimensions.