How to Stub Process.env in Node.js

Asked 1 years ago, Updated 1 years ago, 90 views

I would like to replace process.env for testing purposes.

Currently, we are replacing it as follows.Is there a smarter way?

describe('test', function(){
  beforeEach(function(){
    this.env = process.env;
    process.env = {hoge:123};
  });
  afterEach(function() {process.env=this.env;});
  it('works', function() {/*...*/});
});

In the case of function, I think sinon.stub(obj, 'method', func) would be good in Sinon.JS, but in the case of property, I don't know what to do.

javascript test mock

2022-09-30 20:18

1 Answers

How about using the Sandbox API from Sinon.JS?
Below is the sample code.
With this, I could only stub the PATH environment variable.

varsandbox=require('sinon').sandbox.create();
describe('test', function(){
  beforeEach(function(){
    sandbox.stub(process.env, "PATH", "hoge");
  });
  afterEach(function(){
    sandbox.restore();
  });
  it('works', function() {/*...*/});
});


2022-09-30 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.