Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub process.env in node.js?

I want to stub process.env.FOO with bar.

var sinon = require('sinon'); var stub = sinon.stub(process.env, 'FOO', 'bar'); 

I'm confused. I read document, but still I don't understand yet.sinonjs docs

sinonjs is one example, not sinonjs is okay.

like image 354
Matt - sanemat Avatar asked Jul 05 '14 17:07

Matt - sanemat


People also ask

How process env works in node?

The process. env global variable is injected by the Node at runtime for your application to use and it represents the state of the system environment your application is in when it starts. For example, if the system has a PATH variable set, this will be made accessible to you through process.


2 Answers

From my understanding of process.env, you can simply treat it like any other variable when setting its properties. Keep in mind, though, that every value in process.env must be a string. So, if you need a particular value in your test:

   it('does something interesting', () => {       process.env.NODE_ENV = 'test';       // ...    }); 

To avoid leaking state into other tests, be sure to reset the variable to its original value or delete it altogether:

   afterEach(() => {        delete process.env.NODE_ENV;    }); 
like image 133
Joshua Dutton Avatar answered Sep 20 '22 11:09

Joshua Dutton


I was able to get process.env to be stubed properly in my unit tests by cloning it and in a teardown method restoring it.

Example using Mocha

const env = Object.assign({}, process.env);  after(() => {     process.env = env; });  ...  it('my test', ()=> {     process.env.NODE_ENV = 'blah' }) 

Keep in mind this will only work if the process.env is only being read in the function you are testing. For example if the code that you are testing reads the variable and uses it in a closure it will not work. You probably invalidate the cached require to test that properly.

For example the following won't have the env stubbed:

const nodeEnv = process.env.NODE_ENV;  const fnToTest = () => {    nodeEnv ... } 
like image 34
pllee Avatar answered Sep 19 '22 11:09

pllee