问题
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