How to stub process.env in node.js?

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

    In a spec-helper.coffee or something similar where you set up your sinon sandbox, keep track of the original process.env and restore it after each test, so you don't leak between tests and don't have to remember to reset every time.

    _ = require 'lodash'
    sinon = require 'sinon'
    
    beforeEach ->
        @originalProcessEnv = _.cloneDeep process.env
    
    afterEach ->
        process.env = _.cloneDeep @originalProcessEnv
    

    In your test, use process.env as normal.

    it 'does something based on an env var', ->
        process.env.FOO = 'bar'
    

提交回复
热议问题