search-learn
search-learn

Reputation: 1314

Process.env Variables Not Available Outside of Function During Jest Testing

I ran into an issue where my imported env variables are not available outside of function scope and I wonder if this is an intentional design or am I doing something wrong

For example my setup looks like this

/src/index.test.js

//require config
const config = require('../config.json');
const myFunc = require('./index.js');

beforeEach(async () =>
{
   //set env vars
     process.env = Object.assign(process.env, config);
})

test('sample', async () =>
{
   //call function
   await myFunc();

  expect(somethingMeaninful).toBeCalledTimes(1);
})

And then my actual code looks like this

src/index.js

const myVar = process.env.myVar

console.log(process.env.myVar) //<= will be undefined

async function myFunc()
{
   console.log(process.env.myVar) //<= will show my value from config.json file

    return somethingMeaninful();
}

exports.myFunc = myFunc();

So since myVar is declared outside of function it is undefined. I tried doing console.log() on process.env as a whole inside and outside my func and outside it would have all the default values but inside it would have defaults + my config values as well. Really confused by how and why this happens. Those variables are not undefined when I run my code normally but are undefined during testing...

This link mentions this issue here as well github vue testing issue

Upvotes: 2

Views: 1808

Answers (2)

rishi raj raj
rishi raj raj

Reputation: 11

The same thing happened to me. After scratching my head for a while, I figured out that process.env.SOMETHING will only work inside a function scope

Upvotes: 1

search-learn
search-learn

Reputation: 1314

I think I figured it out. Apparently my jest.config.js file was never being read. And because of this none of the setupFiles or setupFilesAfterEnv were running either.

It was because I had my jest.config.js in <rootDir>/jest because I had in the nested folder called jest it never ran. Moving it out of there into root fixed my issues. And all of my files are being ran as necessary

Upvotes: 1

Related Questions