Home > Back-end >  Cypress - How to have only some env variables checked into source control?
Cypress - How to have only some env variables checked into source control?

Time:10-01

I have two env files, one is development.json and the other production.json. They have a bunch of env variables like so:

{
    "env": {
        "baseUrl": "test.com",
        "freeUserEmail": "test",
        "freeUserPassword": "test123", 
    }
}

The file used is determined in the Cypress config file:

export default defineConfig({
  e2e: {
    async setupNodeEvents(on, config) {
      const version = config.env.version || 'development'
      const configFile = await import(path.join(
        config.projectRoot,
        'cypress/config',
        `${version}.json`
      ));

Scripts look like this:

"cypress:open:dev": "cypress open --env version=development",
"cypress:open:production": "cypress open --env version=production"

However, I want to move account credentials out of these of files into env files that aren't checked into source control but I want to keep the current files for things like baseUrl which I don't need hidden. Is it possible to have multiple env files for one environment? How would one achieve this?

CodePudding user response:

try creating file in fixtures folder e.g. credentials.json and store your credentials there, this way you can even add them to .gitignore file for safety. then just use

cy.fixtures('credentials').then((credentials) => {
     get('someSelector').type(credentails['freeUserEmail'])
})

CodePudding user response:

The below example merges content of all config files from current environment to one configFile object

export default defineConfig({
  e2e: {
    async setupNodeEvents(on, config) {
      const version = config.env.version || 'development'

      const filesPerEnv = {
        'development': ['file1', 'file2'],
        'production': ['someOtherFile', 'someOtherFile2']
      }

      const configFile = {};

      // Loop trough all files per environment
      // Merge each files content to one `configFile`
      filesPerEnv[version].forEach((fileName) => {
        configFile = {
          ...configFile,
          ...(await import(path.join(config.projectRoot, 'cypress/config', `${fileName}.json`)))
        }
      });
  • Related