How to Run Cypress in Headless Mode: Simple Guide
To run Cypress in headless mode, use the command
npx cypress run in your terminal. This runs tests without opening the Cypress Test Runner UI, making it faster and suitable for CI environments.Syntax
The basic syntax to run Cypress in headless mode is:
npx cypress run: Runs all tests headlessly using the default browser (usually Electron).--browser <browser-name>: Optional flag to specify a browser like Chrome or Firefox.--spec <path-to-spec>: Optional flag to run specific test files.
bash
npx cypress run [--browser <browser-name>] [--spec <path-to-spec>]
Example
This example runs Cypress tests headlessly in Chrome browser for a specific test file:
bash
npx cypress run --browser chrome --spec cypress/e2e/sample_spec.cy.js
Output
====================================================================================================
(Run Starting)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Cypress: 12.17.0 โ
โ Browser: Chrome 114 โ
โ Specs: 1 found (sample_spec.cy.js) โ
โ Searched: cypress/e2e/sample_spec.cy.js โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Running: sample_spec.cy.js (1 of 1)
โ visits the example page
1 passing (1s)
(Run Finished)
====================================================================================================
Common Pitfalls
Common mistakes when running Cypress headlessly include:
- Not installing Cypress properly before running
npx cypress run. - Forgetting to specify the browser if you want to use Chrome or Firefox instead of the default Electron.
- Running tests that require UI interaction without proper configuration, causing failures.
- Using
cypress openinstead ofcypress runwhich opens the UI and is not headless.
bash
Wrong: npx cypress open Right: npx cypress run --browser chrome
Quick Reference
| Command | Description |
|---|---|
| npx cypress run | Run all tests headlessly in default browser (Electron) |
| npx cypress run --browser chrome | Run tests headlessly in Chrome browser |
| npx cypress run --spec cypress/e2e/test.cy.js | Run a specific test file headlessly |
| npx cypress open | Open Cypress Test Runner UI (not headless) |
Key Takeaways
Use
npx cypress run to run tests headlessly without UI.Specify
--browser to choose a browser other than Electron.Headless mode is ideal for CI/CD pipelines and faster test runs.
Avoid using
cypress open when you want headless execution.Check your test compatibility with headless browsers to prevent failures.