I am taking a swing at setting up a test suite for my company's web app. We use four environments at the time (Production, Regression, Staging, Development). I have environment variables setup in my cypress.json file but I would like to be able to switch my environment for example from regression to development and force cypress to change the baseURL to my new environment as well as point to a different cypress.json file that has development variables. The documentation around environments on cypress.io is a little confusing to me and I'm not sure where to start.
We can set environment by passing these arguments in the cypress run or cypress open command e.g. cypress open --env configFile=test. This command looks lengthy. Also, sometimes we need to pass more command line arguments along with configFile. We can create short and handy commands by configuring the package.
json. The easiest way to switch environments is to simply rewrite your cypress. json file and set baseUrl to a different value each time you want to switch environments. This is of course tedious and takes way too much work if you need to switch often.
In Cypress, environment variables (accessible via Cypress. env ) doesn't share the same scope as OS-level environment variables. In order to make process. env variables available in Cypress , you should use a third party library, such as dotenv package, which is very popular.
I have cypress running in different environments using package.json's scripts. You can pass in env vars before the cypress command. It would look something like:
"scripts": {
"cypress:open:dev": "CYPRESS_BASE_URL=http://localhost:3000 cypress open",
"cypress:open:prod": "CYPRESS_BASE_URL=http://mycompanydomain.com cypress open",
"cypress:run:dev": "CYPRESS_BASE_URL=http://localhost:3000 cypress run",
"cypress:run:prod": "CYPRESS_BASE_URL=http://mycompanydomain.com cypress run",
}
If you want to make 4 separate cypress.json files instead, you could have them all named according to environment and when you run an npm script that corresponds with that environment just copy it to be the main cypress.json when you run the tests.
Files:
./cypress.dev.json
./cypress.prod.json
./cypress.staging.json
./cypress.regression.json
npm scripts:
"scripts": {
"cypress:run:dev": "cp ./cypress.dev.json ./cypress.json; cypress run;"
}
Update:
I wrote this while cypress was still in beta. Using the config flag seems like a cleaner option:
https://docs.cypress.io/guides/guides/command-line.html#cypress-run
npm scripts:
"scripts": {
"cypress:run:dev": "cypress run -c cypress.dev.json;"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With