'How to use .env variables inside cypress.json file?
I want to use my .env variables inside cypress.json file. As an example of usage:
{
"env": {
"HOST": `${process.env.HOST}`
}
}
So, what I want is, when I type Cypress.env('HOST') anywhere in Cypress, I want to get the process.env.HOST variable
Solution 1:[1]
First of all why not use process.env.HOST inside your spec files. Second if you want to test in different host then what i have been doing is.
Create a folder (eg: configFiles)
Inside this create json files like (eg: host1.json, host2.json)
Inside your json file (in host1.json)
{ "env": { "HOST" : "host1" } }
Inside your plugins folder edit index.js
const fs = require('fs-extra'); const path = require('path');
function getConfigurationByFile(file) { const pathToConfigFile = path.resolve( 'cypress/configFiles',
${file}.json);return fs.readJson(pathToConfigFile); }
module.exports = (on, config) => { const file = config.env.host || 'host1';
return getConfigurationByFile(file); };
Then while running you can use npm cypress run --env host=host1
Solution 2:[2]
This is a late answer but you can achieve this by creating the variable in Plugins (https://docs.cypress.io/guides/guides/environment-variables#Option-5-Plugins)
Documentation states:
// .env file
USER_NAME=aTester
/
// plugins/index.js
require('dotenv').config()
module.exports = (on, config) => {
// copy any needed variables from process.env to config.env
config.env.username = process.env.USER_NAME
// do not forget to return the changed config object!
return config
}
// integration/spec.js
it('has username to use', () => {
expect(Cypress.env('username')).to.be.a('string')
})
Solution 3:[3]
Avoid wrapping your env file in env variable. By the way this should do the job with your file:
Cypress.env("env")["HOST"]
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 | tenish shrestha |
| Solution 2 | mhd031 |
| Solution 3 | Fseee |
