How to stub process.env in node.js?

后端 未结 6 1599
梦毁少年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:32

    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;
       });
    

提交回复
热议问题