简体   繁体   中英

Run tests using different env. variables depending on a command in package.json

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM