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
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": ['cypress.io', 'testing', 'cypress'],
"author": "Walmyr Filho <wlsf82@gmail.com> (https://walmyr.dev)",
"license": "MIT",
"devDependencies": {
"cypress": "^6.4.0"
}
}
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"
},
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.
Top comments (6)
Excellent tutorial! I've been on the hunt for similar content on YouTube and stumbled upon this informative video: youtube.com/watch?v=mGL7rSct3CU . I thought I'd share it here for fellow readers who may find it beneficial
Thank you!
When running the test headless do you still have to have the app running? For example having to do and
npm start
then run the commands outlined in the articleSure, the app should be running so we can test it.
can you create please how to run tests in headless mode but on Jenkins? Thank you!!
Sorry, but I’m not a Jenkins user.
I recommend you read the Cypress official, on the Continuous Integration section.