Let's say you want to separate Cypress configuration and Cypress.env
variables for each environment. You might want to store the values in separate JSON files like local.settings.json
, staging.settings.json
, prod.settings.json
, etc. Here is how you can load these settings in Cypress v12.
🎁 You can find the source code for this post in the repo bahmutov/cypress-load-env-by-name-example.
Application
My application is a page that shows a <h1>
greeting. If it is running on staging staging.acme.co
, then it shows the greeting Hi (staging)
, and locally it shows Hi (local)
text. To simulate staging and production environments I made several self-signed SSL certificates following the blog post Cypress Hosts Option:
1 | $ mkcert -key-file ./.cert/staging-key.pem -cert-file ./.cert/staging-cert.pem "staging.acme.co" |
Different environments are running locally by starting with self-signed certificates:
1 | { |
Cypress setup
Let's put the baseUrl
and the expected greeting text into 3 different JSON files, one per environment we want to test.
1 | { |
1 | { |
1 | { |
We want to load these settings based on the name "local", "staging", "prod". We can implement this logic in our cypress.config.js
file
1 | const { defineConfig } = require('cypress') |
Super, we got the JSON with an object. It has the baseUrl
and env
object. We probably want to overwrite the baseUrl
and merge the environment objects. Here is our complete setupNodeEvents
callback code:
1 | setupNodeEvents(on, config) { |
It is very important to return the updated config
object to the caller, so Cypress knows to use the changes configuration.
We only have a single test.
1 | it('checks the page', () => { |
Local server
Let's start the local server
1 | $ npm start |
Now let's open Cypress with the local
settings
1 | $ npx cypress open --env environmentName=local |
Close Cypress and the application and start the staging app. First, the app:
1 | $ npm run start:staging |
Then open Cypress
1 | $ npx cypress open --env environmentName=staging |
Finally, let's start the production application
1 | $ npm run start:prod |
And open Cypress with production settings
1 | $ npx cypress open --env environmentName=prod |
Beautiful, isn't it.
See also
- 📝 blog post Use Cypress Task To Avoid Cypress Env Variable
- 📝 blog post Cypress Hosts Option
- 📺 video How to correctly use the baseUrl to visit a site in Cypress