How to refer to environment variables in Cypress config files?

Viewed 956

I've read Environment Variables in Cypress and other articles regarding passing environment variables in Cypress runs. However how can I refer to the environment variables in my JSON config files?

For example, I do

$ npm run cy:open -- --config-file config/mytests.json --env db.user=db_user,db.password=pw1234abcd

because I want to avoid hard-coding the DB creds in my config file, like this

{
  ...
  "env" : {
    "db" : {
      "user" : "db_user",
      "password" : "pw1234abcd"
    }
  }
}

But what's the syntax in the JSON file to use the passed-in values? What should this look like?

{
  ...
  "env" : {
    "db" : {
      "user" : "???syntax???",
      "password" : "???syntax???"
    }
  }
}
1 Answers

Your config file is just one source of env variables, the command line is another.

At runtime, they are merged in memory and can be accessed with Cypress.env.

// cypress.json
{
  "env": {
    "foo": "bar",
    "baz": "quux"
  }
}

npm run cy:open -- --env user=db_user

Cypress.env() // => { foo: "bar", baz: "quux", user: "db_user" }

In the Cypress runner, click Settings/Configuration to see the merged env object.


Passing variables through the command line is a bit limiting, all "nested" type keys (with a '.') are merged in a flat manner, i.e

// cypress.json
{
  "env": {
    "foo": "bar",
    "baz": "quux"
  }
}

npm run cy:open -- --env db.user=db_user,db.password=pw1234abcd

Cypress.env() 
/* => { 
  foo: "bar", 
  baz: "quux", 
  db.user: "db_user", 
  db.password: "pw1234abcd" 
} */

But you can apply a reducer to the env object to get a nested structure,

const env = Cypress.env();

Object.keys(env)
  .reduce((env, key) => {
    if (key.includes('.')) {
      const [parent, child] = key.split('.');
      if (!env[parent]) {
        env[parent] = {};
      }
      env[parent][child] = env[key];
      delete env[key];
    }
    return env;
  }, env)

Cypress.env(env); // save back to Cypress if required

console.log(env);

/* => { 
  foo: "bar", 
  baz: "quux", 
  db: {
    user: "db_user", 
    password: "pw1234abcd"
  }
} */

Add this at the top of the test, or in cypress/support/index.js.

Related