Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda