Skip to content
Advertisement

How to set Node Environment as Env Variable in the middle of the app?

I know that I can do process.env.NODE_ENV = TEST but it is not working for me. Relevant code below:

test.js

JavaScript

src/index.js

JavaScript

user.js

JavaScript

So the issue here is that when I run test.js, I am importing, and therefore running user.js before I set my NODE_ENV. Since imports are hoisted I can’t bring the env setting earlier either. However, I need the user.js to behave differently when I am testing, and hence I need to set the NODE_ENV before running user.js code. How can I achieve that?

Edit: I tried changing my test script to ‘test: SET NODE_ENV=test && mocha’. This seems to set the node env but I am still facing issue.

user.js

JavaScript

Somehow the 2 ‘test’ are different? There is also the issue of SET being Windows-specific.

Advertisement

Answer

For now I have settled with installing cross-env and doing

“test” : “cross-env NODE_ENV=test mocha”

but would love to hear better suggestions.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement