Regarding the discussion in this issue for Sinon 2 I found the migration documentation to be lacking on migrating from this:
const sandbox = sinon.sandbox.create();
sandbox.stub(process, 'env', {SOME_KEY: 'some value'});
sandbox.restore();
However after some troubleshooting this seems to work for Sinon 3:
const sandbox = sinon.sandbox.create();
sandbox.stub(process, 'env').value({ 'SOME_KEY': 'some value' });
sandbox.restore();
Just wanted to leave this information for anybody having the same problem since the original thread is locked.
@Siilweyn, if you think this is a shortcoming that should be addressed, feel free to push a small correction to the docs!
This also works sinon.stub(process.env, 'NODE_ENV').value('FAKE_ENV');
The approach by @lkashef is probably the better/safer approach, as it is not overwriting all existing values in the env field.
@fatso83 I am not sure which approach you are referring to.
@lkashef Updated wording. Sorry for being unclear.
No worries @fatso83, thanks for the confirmation.
I like the approach described by @lkashef but note it won't work for environment variables that are not previously set (TypeError: Cannot stub non-existent own property NODE_ENV).
EDIT: Just realised it's still possible to maintain the existing process.env properties if desired:
sandbox.stub(process, 'env').value({ ...process.env, 'SOME_KEY': 'some value' });
What I need is
const env = propess.env;
sinon.stub(propess.env, 'KEY').value('VALUE'); // fails with TypeError: Cannot stub non-existent property KEY
expect(env.KEY).toEqual('VALUE');
But it does not work, because it is unable to stub non-existing object property.
Suggested solution is
const env = propess.env;
sinon.stub(propess, 'env').value({ ...propess.env, KEY: 'VALUE' });
expect(env.KEY).toEqual('VALUE'); // fails due to env.KEY is undefined
But it is not applicable, because stub won't affect any property of const env;
Most helpful comment
I like the approach described by @lkashef but note it won't work for environment variables that are not previously set (
TypeError: Cannot stub non-existent own property NODE_ENV).EDIT: Just realised it's still possible to maintain the existing
process.envproperties if desired: