Skip to content

Instantly share code, notes, and snippets.

@lwkchan
Last active May 29, 2020 13:19
Show Gist options
  • Save lwkchan/1e477dd73dd4959a530713359c9631e7 to your computer and use it in GitHub Desktop.
Save lwkchan/1e477dd73dd4959a530713359c9631e7 to your computer and use it in GitHub Desktop.

Testing with env vars

To test with different kinds of env vars in different unit tests we need to do the following.

  1. set up the vars on process.env.NODE_ENV
  2. run the test
  3. 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.

setting up vars on process.env.NODE_ENV and running the test

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.

Reset it

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'],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment