how to override an environment variable for different test cases in nodeJS?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 10:42:24

问题


I am using dotenv to load the .env file, but I need to run the test cases for different values of a particular environment variable. But unfortunately, once loaded dotenv does not let me change the value of the env variable, I can not reset the value again.

What could be an alternate approach for this?


回答1:


You should have only those variables as environment variables that don't affect your code. For example, the database host, passwords, api keys etc.

I suggest you that you make 3 env files - dev, test, production. And use those.




回答2:


You can have multiple versions of the .env file with the different values you want to test for. You can invoke the different configurations by parsing alternate versions of the config file using the parse method of dotenv.

Ex:

var dotenv = require('dotenv');
var fs = require('fs');

var config1 = dotenv.parse(fs.readFileSync('/path/to/config1'));
var config2 = dotenv.parse(fs.readFileSync('/path/to/config1'));
var config3 = dotenv.parse(fs.readFileSync('/path/to/config1'));


来源:https://stackoverflow.com/questions/48258670/how-to-override-an-environment-variable-for-different-test-cases-in-nodejs

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