Home > Mobile >  How to use env variable in app.js in node.js when debugging test?
How to use env variable in app.js in node.js when debugging test?

Time:10-19

When I debug on visual studio app.js is run before test codes and env config files

How to set env on app.js?

If I deploy or test on terminal I can use envs on app.js and check env from log But not on debug.

a.test.js

const { describe, it } = require('mocha');
const request = require('supertest');
const { expect } = require('chai');
const { setConfig } = require('../../../setConfig');
const { app } = require('../../../../app');

setConfig();

describe('transactionController', () => {
  it('test', async () => {
    await request(app)
      .post(`/`)
      .set('Accept', 'application/json')
      .type('application/json')
      .send()
      .expect(200);
  });

setConfig.js

const { config } = require('../config/config');

module.exports.setConfig = () => {
  console.log(`setConfig : ${JSON.stringify(config.debug)}`);
  const { debug } = config;
  const { NODE_ENV, CACHE_HOST, CACHE_PORT } = debug;

  process.env.NODE_ENV = NODE_ENV;
  process.env.CACHE_HOST = CACHE_HOST;
  process.env.CACHE_PORT = CACHE_PORT;
};

config.js

module.exports.config = {
  debug: {
    NODE_ENV: 'debug',
    CACHE_HOST: '127.0.0.1',
    CACHE_PORT: '6379'
  },
};

app.js

const serverless = require('serverless-http');
const express = require('express');

const app = express();

app.set('port', 3000);

console.log(`app : env : ${process.env.NODE_ENV}`);
if (process.env.NODE_ENV === 'prod' || process.env.NODE_ENV === 'dev') {
  app.listen(app.get('port'), () => {
    console.log(`Server running on ${app.get('port')} port`);
  });
  module.exports.app = serverless(app);
} else {
  module.exports.app = app;
}

CodePudding user response:

In your launch.json (the file where you set up your debugger) you can add this to the configuration :

"env": {
    "NODE_ENV": "debug",
    "CACHE_HOST": "127.0.0.1",
    "CACHE_PORT": "6379"
}

It will add all the env variable you want when you launch the debugger

  • Related