1) You should better encapsulate your checks:
const allowedEnvironments = ['local', 'development', 'production'];
class AppEnv {
constructor(env) {
if (!env) {
throw Error('Process environment is required!');
}
if (!allowedEnvironments.includes(env)) {
throw Error('Process environment not allowed! Choose another!');
}
this._env = env;
}
get isLocal() {
return this._env === 'local';
}
get isDevelopment() {
return this._env === 'development';
}
get isProduction() {
return this._env === 'production';
}
}
export { AppEnv };
2) Then you could write tests for it without process.env
:
import { AppEnv } from './app-env';
describe('AppEnv', () => {
const createAppEnv = (env: string) => new AppEnv(env);
it('should throw for empty env', () => {
expect(() => createAppEnv('')).toThrow();
});
it('should throw for bad env', () => {
expect(() => createAppEnv('_bad_env_value_')).toThrow();
});
it('should be local', () => {
expect(createAppEnv('local').isLocal).toBe(true);
});
it('should be development', () => {
expect(createAppEnv('development').isDevelopment).toBe(true);
});
it('should be production', () => {
expect(createAppEnv('production').isProduction).toBe(true);
});
});
3) In your config.js instantiate the AppEnv
with process.env.NODE_ENV
:
import { AppEnv } from './app-env';
const appEnv = new AppEnv(process.env.NODE_ENV);
export { appEnv };
4) Use the appEnv
everywhere in your application:
import { appEnv } from './config';
if (appEnv.isDevelopment) {
// do something
}