How to stub process.env in node.js?

后端 未结 6 1602
梦毁少年i
梦毁少年i 2021-02-02 04:56

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

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


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 05:22

    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 ...
    }
    

提交回复
热议问题