Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change process.env variable for single test using JEST [duplicate]

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';
  ...
});
like image 436
CoryDorning Avatar asked Nov 15 '25 21:11

CoryDorning


1 Answers

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 caveats 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

like image 198
Johannes Merz Avatar answered Nov 17 '25 10:11

Johannes Merz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!