How to refer to environment variables in Cypress config files?

早过忘川 提交于 2021-01-03 06:21:29

问题


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:


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.



来源:https://stackoverflow.com/questions/65191104/how-to-refer-to-environment-variables-in-cypress-config-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!