Home > OS >  Using environment variables in Node and Jest
Using environment variables in Node and Jest

Time:06-13

I have a NodeJS app. For a long time I've been using Mocha to run tests. I simply had a package.json like

"dev": "node index --env=dev",
"start": "node index",
"test": "mocha './test/**/*.spec' --env=dev"

Now I am switching to Jest for a variety of reasons, and the test script becomes simply

"test":"jest"

Within my test suites, I spin up an instance of my app. In functions throughout my app there are decisions based on the environment. Simplified example:

const ProcessArgs = require("minimist")(process.argv);

export function uploadImage(image){
   if(ProcessArgs.env === "dev"){
      return writeToLocalTestFolder(image);
   }
   else {
      return uploadToCloud(image);
   }
}

So this used to look at the --env=dev arg, but that's no longer there. (If I try to add --env=dev to Jest, well that's an entirely different issue). I do in fact properly use Heroku's secrets for my actual important env variables like API keys, etc, but I now seem to be stuck here on how I should tell Jest what env it is in, since it needs env=node to work properly.

CodePudding user response:

Mocking out environment variables in Jest is a little bit more tricky as there really is no way to mock them out before the code that you want to import gets evaluated. However, there is a handy workaround. You can mock out the library that is contains the environment variables and have it return specifically what you need.

Referring to your example, you can mock out what environment variables are returned by minimist by using the following code (make sure it is used before the describe of your test suite:

jest.mock('minimist', () => {
  return () => ({ env: 'dev'});
});

The if(ProcessArgs.env === "dev"){ conditional check should run as expected.

  • Related