I want to stub process.env.FOO
with bar
.
var sinon = require('sinon');
var stub = sinon.stub(process.env, 'FOO', 'bar');
I'm confused. I read document, but still I don't understand yet.sinonjs docs
sinonjs is one example, not sinonjs is okay.
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
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:
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 inprocess.env
must be a string. So, if you need a particular value in your test:To avoid leaking state into other tests, be sure to reset the variable to its original value or delete it altogether:
With sinon you can stub any variable like this.
This example is form sinon documentation. https://sinonjs.org/releases/v6.1.5/stubs/
With that knowledge, you can stub any environment variable. In your case it would look like this:
How to quickly mock process.env during unit testing.
https://glebbahmutov.com/blog/mocking-process-env/
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
In a
spec-helper.coffee
or something similar where you set up your sinon sandbox, keep track of the originalprocess.env
and restore it after each test, so you don't leak between tests and don't have to remember to reset every time.In your test, use
process.env
as normal.