To test with different kinds of env vars in different unit tests we need to do the following.
- set up the vars on
process.env.NODE_ENV
- run the test
- reset it
Step three is very important since process.env
is a global variable, we want to make sure that when every test uses it, it returns what is expected.
To do this, we write a function which does this for us
const setUpProductionEnv = () => {
process.env.NODE_ENV = 'production';
}
Then to use it we can either use it in a beforeEach block before certain assertions in a test suite, or at the beginning of a test
describe('Stuff in production', () => {
beforeEach(() => {
setUpProductionEnv()
})
it('works in production', () => {
// assert stuff for production
})
})
it('works in production', () => {
setUpProductionEnv();
// assert stuff for production
})
I personally like this approach because it is very clear when the production env is being used.
Because process.env.NODE_ENV
is global, once we set it somewhere, we should reset it before the next test, otherwise the next test's behaviour might be unexpected.
When you are writing a new test, is no way at the beginning of a test to tell what process.env.NODE_ENV
is. Moreover, unless specified manually, there is no way to guarantee that the test suites will run in a certain order., we might test something with an unexpected.
To do this we should create an all-test afterEach block which resets the process.env.NODE_ENV to the default node env (which is just 'test' in jest, if non is specified elsewhere). To do this, we create a file with the following
const DEFAULT_ENV = 'test'
afterEach(() => {
process.env.NODE_ENV = DEFAULT_ENV;
})
and we connect it to jest by adding it to our jest config's setupFilesAfterEnv
property
module.exports = {
setupFilesAfterEnv: ['<rootDir>/jest-setup/afterEnv.js'],
};