How to stub process.env in node.js?

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

    How to quickly mock process.env during unit testing.

    https://glebbahmutov.com/blog/mocking-process-env/

    const sinon = require('sinon')
    let sandbox = sinon.createSandbox()
    
    beforeEach(() => {
      sandbox.stub(process.env, 'USER').value('test-user')
    })
    
    it('has expected user', () => {
      assert(process.env.USER === 'test-user', 'wrong user')
    })
    
    afterEach(() => {
      sandbox.restore()
    })
    

    But what about properties that might not exist in process.env before the test? You can use the following package and then you will be able to test the not exist env variables.

    https://github.com/bahmutov/mocked-env

提交回复
热议问题