I know that I can do process.env.NODE_ENV = TEST but it is not working for me. Relevant code below:
test.js
import server from "../../src/index.js"; process.env.NODE_ENV = "test"; console.log(process.env.NODE_ENV); // returns "test" chai.use(chaiHttp); // calls server here with chai-http
src/index.js
import express from "express"; import dotenv from "dotenv"; dotenv.config(); const app = express(); // Some API endpoint here that calls getUserFromUserId app.listen(port, () => { logger.info(`App running on http://localhost:${port}`); }); export default app;
user.js
console.log(process.env.NODE_ENV) // returns undefined process.env.NODE_ENV = "test" // manually sets it here again console.log(process.env.NODE_ENV) // returns test correcly this time
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
console.log(process.env.NODE_ENV); // returns test console.log(process.env.NODE_ENV === "test"); // returns false process.env.NODE_ENV = "test"; console.log(process.env.NODE_ENV); // returns test console.log(process.env.NODE_ENV === "test"); // returns true
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.