Reputation: 525
Trying to find a common practice solution of how to run tests depending on test command in package.json with corresponding environment variables from .env file.
.env. //file
BASE_URL=dev
BASE_URL=stage
API_DEV=api-dev
API_STG=api-stage
package.json //file
"test:dev": "mocha ...",
"test:stage": "mocha ...",
Launching test:dev I want to fetch for my tests all variables for DEV environment.
Can I configure it like that?
Upvotes: 0
Views: 1636
Reputation: 525
Ok, I solved it like that:
In config
folder I have
.env
stage.env
prod.env
and have index.js
file where:
const {NODE_ENV = 'dev'} = process.env;
const dotenv = require('dotenv').config({path: `${__dirname}/${NODE_ENV}.env`});
module.exports = {
api: {
url: dotenv.parsed.API_BASE || ''
},
elastic: {
host: dotenv.parsed.ELASTIC_HOST || ''
}
};
and in package json I have:
"elastic:dev": "mocha ./test/elasticsearch/*.js",
"elastic:stage": "NODE_ENV=stage mocha ./test/elasticsearch/*.js",
"elastic:prod": "NODE_ENV=prod mocha ./test/elasticsearch/*.js"
Easy and pretty dry way to start tests aka like a boss depending on the environment.
Upvotes: 0
Reputation: 3830
Lets say your package.json
contains the following scripts property-
"test:local": "APP_ENV=local mocha ...",
"test:dev": "APP_ENV=dev mocha ...",
"test:stage": "APP_ENV=stage mocha ...",
"test:prod": "APP_ENV=prod mocha ..."
And lets assume you have the following files: .env
for prod
, .env.stage
for stage
and .env.dev
for dev
environment.
Now in your script you can dynamically load the env
files using dotenv
package.
switch (process.env.APP_ENV) {
case 'dev':
env_suffix = ".dev";
break;
case 'stage':
env_suffix = ".stage";
break;
case 'local':
env_suffix = ".local";
break;
}
require("dotenv").config({
path: path.join(__dirname + "/../", ".env" + env_suffix)
});
In this way you can have the environment variables in your process.env
object
Upvotes: 2