3

I have a .env file with MYVAR=1 variable in it.

server.js

//...   
var app = express();  
//... 
if(app.get("env")==="development"){
  require('dotenv').config();
}
console.log("server------",process.env. MYVAR) //outputs 1
if(process.env.MYVAR==1){
   //do this  
}
if(process.env.MYVAR==2){
   //do this 
}
module.exports = app;

test.server.js

app = require('../server'),
supertest = require('supertest');
require('dotenv').config();

describe('Server TESTS', function () {
    let request = null
    let server = null

    before(function (done) {
        process.env.MYVAR = 2;
        server = app.listen()
        request = supertest.agent(server)
        done()
    });

    after(function (done) {
        console.log("client------",process.env. MYVAR) //outputs 2
        server.close(done)
    });

})

Problem: After I run mocha test, my MYVAR does not reflect server.js file and it remains as 1. Even if I comment out require('dotenv').config(); in server.js

How do I overcome this, maybe my supertest agent structure is not correct. Please advice.

UPDATE:

Instead of server = app.listen(), server = require('../server').listen()
worked as expected.

InGeek
  • 2,532
  • 2
  • 26
  • 36

2 Answers2

4

Just try to call process.env.MYVAR = 2; before app = require('../server'):

require('dotenv').config();
process.env.MYVAR = 2;
var app = require('../server');
var supertest = require('supertest');

There is a better way to handle test environment variables you can create a test/mocha.env.js file and then add --require test/mocha.env.js to mocha.opts, but still it depends on what you need.

Pavlo Zhmak
  • 151
  • 1
  • 5
  • I need to change MYVAR dynamically on each test case – InGeek Jul 10 '18 at 18:12
  • Are you sure that you need environment variables for this? But anyway the main problem is that your script is running before you initialize MYVAR. So, you can wrap the code that uses those variables in a function and call it after `process.env.MYVAR = 2;` – Pavlo Zhmak Jul 10 '18 at 19:04
  • Instead of `server = app.listen()`, `server = require('../server').listen()` worked as expected. – InGeek Jul 10 '18 at 19:23
  • If it comes to extensively testing this neat litte npm package mentioned [here](https://stackoverflow.com/a/31505483/810568) is very useful too. – ThreeCheeseHigh Dec 02 '20 at 23:35
2

I've found unit testing code that uses process.env is much easier if you move it to a separate module and stub that out during test:

// config/env.js
export default process.env;

// server.js
import env from 'config/env';

if (env.MYVAR === 2) {
  ...
}

// server.test.js
// stub config/env.js with library of your choice
Alan Friedman
  • 1,582
  • 9
  • 7