Often, the behavior of the program is controlled by the environment variables at its startup. In Node, all these variables are stored in process.env object, where is value is cast as string ⚠️ (this makes process.env different from "regular" JavaScript objects, because we have to take it into account).
If you want to see the process.env just execute node -e 'console.log(process.env)' from the terminal. Notice how all values are strings?
1 | { |
I love sinon.js, so my first approach was to use it to mock process.env. Sinon allows me to quickly stub existing process.env properties during unit testing. For example, the following works:
1 | const assert = require('assert') |
Great, but what about properties that might not exist in process.env before the test? After searching through the docs and GitHub issues, I could only conclude that Sinon does not allow you to add a mock property temporarily. To the NPM registry search! I found burl/mock-env, but its syntax was really weird. So I finally coded mocked-env, check it out.
1 | const mockedEnv = require('mocked-env') |
Happy testing!
- Mock system APIs
- Mocking vs Refactoring
- and lots of my other testing posts