Reputation: 9837
I'm working on a project that uses the value in process.env.APP_ENV
in order to select the appropiate config file for the current environment:
import prodParams from './production';
import stgParams from './staging';
import devParams from './development';
let params = devParams;
switch (process.env.APP_ENV) {
case 'production':
params = prodParams;
break;
case 'staging':
params = stgParams;
break;
default:
params = devParams;
}
export default params;
I'm trying to test this with the following code (not yet with assertions):
import params from '../../../parameters';
...
it.only('should return the appropriate config ', (done) => {
process.env.APP_ENV = 'production';
console.log(params);
done();
});
However when I set environment variable process.env.APP_ENV
as shown above it still reaches the module as undefined, so it always returns the development config instead of the production environment.
Setting aside the test part, the functionality is working fine, but I would like to test it regardless.
Any suggestions on how to fix this?
Upvotes: 2
Views: 1478
Reputation: 203286
import
statements are executed before any other code, so you can't make this work using import
.
You can somewhat get it working with require
, if you require the parameters file after you have set the environment variable:
process.env.APP_ENV = 'production';
let params = require('../../../parameters').default;
...
However, this still isn't great, because it'll work just once because of the cache that require
maintains (a subsequent test which sets APP_ENV
to a different value won't work).
A workaround would be to have parameters.js
export a function that you'd call:
// parameters.js
export default function() {
let params = devParams;
switch (process.env.APP_ENV) {
...
}
return params;
}
// test.js
import getParams from '../../../parameters';
...
process.env.APP_ENV = 'production';
let params = getParams();
Or set APP_ENV
externally:
$ env APP_ENV='production' mocha ...
Upvotes: 2