A couple of years back (which seemed like an eternity), I wrote this piece where we can use environment json files to easily switch between environment variables in Cypress.
However, since the use of plugin/index.ts
/ plugin/index.js
is deprecated (or highly discouraged) now with Cypress 10+, a little tweaking is required to utilise cypress.config.js
/ cypress.config.ts
without impacting much of the codebase (considering my rusty Cypress skills now). News flash: the legacy index
file can still be used so read til the end of this 😉.
Though I'm still not a fan but we are using Typescript now 🫢 in my new company so if you are using Javascript, just do some refactoring.
Here's my new code all in cypress.config.ts
file:
const localEnv = {
"domain": "localhost:8080",
"description": "This is my local machine!",
"protocol": "http://",
"subDirectory": "helloworld"
};
const testEnv = {
"domain": "test1.domain.com",
"description": "This is the awesome stage environment",
"protocol": "https://",
"subDirectory": "/helloworld"
};
const envConfig = (environment) => {
switch(environment) {
case 'local': return localEnv;
case 'test':
default: return testEnv;
}
};
e2e: {
env: {
...envConfig(process.env.ENVIRONMENT?.toString()), // override with the environment configuration based on the value passed in CI (e.g. ENVIRONMENT=test)
grepFilterSpecs: true,
},
},
Note that we can still add other environment variables that is generic to all environments like grepFilterSpecs
so we don't need to include it in each of the configs.
Basically, the premise is we can only use Cypress.env
on the test specs but since config.config.ts
runs in node as part of the setup process, then we can't use it yet. It can be reached using process.env
. So, when you use something like ENVIRONMENT=test npx cypress run
on your CLI, the following will appear on the Project settings of your Cypress runner:
BONUS: The legacy index
file can still be used with the following lines on cypress.config
file:
const legacyConfig = require('./cypress/plugins/index');
...
e2e: {
setupNodeEvents(on, config) {
return legacyConfig(on, config); // since we still use the old plugin file to override configs
}
Top comments (0)