Home > Blockchain >  Change process.env variable for single test using JEST
Change process.env variable for single test using JEST

Time:02-11

i have the following code in a file that i'm trying to test:

foo.js

let localEnv = (process.env.LOCAL_ENVIRONMENT).toLowerCase() === 'prod' ? 'prod' : 'stage';

currently, i set this value using setupFiles which points to env.js and it contains:

process.env.LOCAL_ENVIRONMENT = 'prod';

my question is, how do i change process.env.LOCAL_ENVIRONMENT to test (or anything else) in foo.test.js? Just need to do this in a single test, so this line will be covered in my test coverage.

I tried doing something like this but it didn't work...

foo.test.js

test('Nonprod', async () => { 
  process.env.LOCAL_ENVIRONMENT = 'test';
  ...
});

CodePudding user response:

You can alter the value as you tried. However you have to take into account that in your original file you only access the variable when you first load this script. In order to make this work you have to do sth like this:

// in your test file foo.test.js
const prev = process.env.LOCAL_ENVIRONMENT
process.env.LOCAL_ENVIRONMENT = 'test'; // from now on the env var is test
const myModule = require('./foo.js'); // foo.js is executed and the var is read as test
process.env.LOCAL_ENVIRONMENT = prev; // change value back

This has some caveheats as you cant test multiple scenarios with this (as the module is only loaded in once).

If you want to test more scenarios you have multiple options:

One would be to split the logic and process.env.LOCAL_ENVIRONMENT apart, for example

function getLocalEnv(env = process.env.LOCAL_ENVIRONMENT) {
  return env.toLowerCase() === 'prod' ? 'prod' : 'stage';
}

This function is now very easy to test and doesn't depend on env vars for that anymore

CodePudding user response:

The most easier way to test it for a specific test case is to set the test into a describe scope and to apply / remove the env value in beforeAll / afterAll or beforeEach / afterEach hooks depending on your needs.

describe('Test example', () => {
  describe('prod (default)', () => {
    test('do the thing', () => {
      doTheThing(); // process.env.LOCAL_ENVIRONMENT is by default 'prod' because of your setupFiles
    });
  });
  describe('test env', () => {
    const oldEnv = process.env.LOCAL_ENVIRONMENT; // or { ...process.env } to copy the whole env

    beforeAll(() => {
      process.env.LOCAL_ENVIRONMENT = 'test';
    });
    afterAll(() => {
      process.env.LOCAL_ENVIRONMENT = oldEnv; // do not forget to do this
    });

    test('do the thing', () => {
      doTheThing(); // process.env.LOCAL_ENVIRONMENT is 'test' here
    });
  });
});
  • Related