DEV Community

Cover image for How to run tests in headless mode with Cypress
Walmyr Filho
Walmyr Filho

Posted on • Updated on

How to run tests in headless mode with Cypress

Today in "Pinches of Cypress", learn how to run tests in headless mode

After installing Cypress, you can run cypress open to execute interactive mode tests. You can watch tests run in such a mode, besides having time-travel and automatic-reload features at your disposal.

However, after the tests are ready, we want to automatically execute them for each code change in the application under test, such as when creating and updating pull requests, merging to the main branch, or even after deployments in production.

The good news is that in addition to being powerful, Cypress is a simple tool.

To run the tests in headless mode, use the cypress run command.

And, if you want to run only one specific spec file, you can pass it as an argument to the cypress run command (see below).

cypress run --spec cypress/integration/example.spec.js
Enter fullscreen mode Exit fullscreen mode

Note: It is necessary to prefix the above commands with npx when executing them locally if they are not npm scripts.

Note 2: It's recommended to create npm scripts in the package.json file with shortcuts to execute such commands. See an example below.

  "name": "sample-project",
  "version": "1.0.0",
  "description": "Sample project for the Pinches of Cypress series",
  "main": "index.js",
  "scripts": {
    "test": "cypress run"
  "keywords": ['', 'testing', 'cypress'],
  "author": "Walmyr Filho <> (",
  "license": "MIT",
  "devDependencies": {
    "cypress": "^6.4.0"
Enter fullscreen mode Exit fullscreen mode

With the test script above, instead of running npx cypress run on the terminal, you can simply run npm test, or npm t, for short.

And you can have as many scripts as you want. For example:

"scripts": {
  "cypress:open": "cypress open",
  "cypress:ci": "cypress run",
  "cypress:smoke-test": "cypress run --spec cypress/integration/smoke-test.spec.js"
Enter fullscreen mode Exit fullscreen mode

And to run the scripts above, just run npm run cypress:open, npm run cypress:ci, or npm run cypress:smoke-test.

Are you enjoying the "Pinches of Cypress" series?

I'm looking forward to hearing your feedback!

This post was originally published in Portuguese on the Talking About Testing blog.

Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.

Discussion (0)