'Can we change the cypress.env.json file name

I want to use different environment variable file for prod environment and non prod environments. Currently I'm maintaining a single file for all environment and going forward each env file content will be get different according the environment. Hence is there a possibility to rename the file according the environment and pass it at run time or define the respective env file at a configuration file (cypress.json)

Sample env file names: cypress.env.nonprod.json cypress.env.prod.json



Solution 1:[1]

You can add scripts into project.json file:

{
  "scripts": {
    "setEnvDev": "cp cypress.env.dev.json cypress.env.json",
    "setEnvStaging": "cp cypress.env.staging.json cypress.env.json",
    "setEnvSproduction": "cp cypress.env.production.json cypress.env.json"
  }
}

And run

$ npm run setEnvDev  
$ npx cypress run  

Solution 2:[2]

You can create cypress configuration files in your project root. Like for example if you have three config files:

  • production.json
  • staging.json
  • dev.json

Then depending on what configuration file you want to use, you can directly run the command:

npx cypress run --config-file staging.json

Solution 3:[3]

Set up cypress.env.nonprod.json and cypress.env.prod.json for envrionment-specific, and cypress.env.json for common variables.

In cypress/support/index.js add

const env = Cypress.env()  // configured env from common cypress.env.json + command line

if (env.nonprod) {         // has nonprod environment been set?
  const addEnv = require('cypress.env.nonprod.json')
  const merged = {...env, ...addEnv}
  Cypress.env(merged)      
}

if (env.prod) {         // has prod environment been set?
  const addEnv = require('cypress.env.prod.json')
  const merged = {...env, ...addEnv}
  Cypress.env(merged)      
}

Run from command line (or set up script)

npx cypress run --env nonprod=true

This allows "stacking" where multiple files can be merged

npx cypress run --env nonprod=true,prod=true

Solution 4:[4]

Using cypress/plugins.index.js to merge named environment variable file

// plugins/index.js

module.exports = (on, config) => {

  if (config.env.environment) {
    const envars = require(`cypress.env.${config.env.environment}.json`
    config.env = {
      ...config.env,
      ...envars
    }
  }

  return config
}

To add cypress.env.nonprod.json to base config (cypress.json)

npx cypress run --env environment=nonprod  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SuchAnIgnorantThingToDo-UKR
Solution 2 Alapan Das
Solution 3 TesterDick
Solution 4