Is it possible to enable changing a variable at runtime?
bcanseco opened this issue · 1 comments
bcanseco commented
This could be pretty useful for unit tests:
// source.js
import {NODE_ENV} from '@env';
export const doSomethingBasedOnEnvironment = () => {
if (NODE_ENV === 'production') {
// business logic here
return true;
} else {
// business logic here
return false;
}
};
// source.spec.js
import {doSomethingBasedOnEnvironment} from '.';
import * as env from '@env';
it('should return true in production', () => {
env.NODE_ENV = 'production';
expect(doSomethingBasedOnEnvironment()).toBeTruthy();
});
it('should return false in development', () => {
env.NODE_ENV = 'development';
expect(doSomethingBasedOnEnvironment()).toBeFalsy();
});
Maybe a contrived example, but in real-world applications the current alternatives aren't ideal:
- Edit the API only for the tests' sake:
// source.js import {NODE_ENV} from '@env'; export const doSomethingBasedOnEnvironment = (environment = NODE_ENV) => { if (environment === 'production') { return true; } else { return false; } };
- Fall back to exclusively using
process.env
due to the problem below:import {NODE_ENV} from '@env'; process.env.NODE_ENV = 'something-else'; expect(NODE_ENV).toEqual('something-else'); // throws
goatandsheep commented
what you can do is make a file and call it .env.test
. This really isn't the purpose of environment variables.