Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda