Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[node][mocha]Global variables not accessible when testing with mocha

I'm trying to create a unit test for express node application. I want the configuration used for the test to be different than the one used in production, so I implemented the following.

In my index.js, I load the configuration into the global variable like this:

global.env = {};
global.env.config = require('./config/config');
// Create the server ...
server.listen(3000);

module.exports = server;

In some other controller myController.js, I access the global variable like this

var Config = global.env.config

When I launch this using node index.js it works just fine.

But when I use mocha with proxyquire to override the config:

describe('myController', function () {
    describe("#myMethod", () => {

        it("must work", (done) => {
             const config = {
                INPUT_FILE_DIR: path.resolve('../ressources/input/')
             }

             const server = proxyquire('../index.js', { './config/config': config })// error in this line
        })
    })
})

I have an error telling that myController can't read the property config

Cannot read property 'config' of undefined

Thanks for your help

like image 537
abderrahim_05 Avatar asked Jan 01 '23 05:01

abderrahim_05


1 Answers

This is how I would have approached it. Firstly, i would export config as a function instead of an object.

The reason is the code will have a better structure and easy to maintain. Also there's no need to expose the config globally, as that could pose some security risk.

export const getConfig = () => {
  if(process.env.NODE_ENV==="production"){
    return require('./production.config');
  }
  return require('./default.config');
};

In my test file, I would mock the function call using sinonjs like below.

const configModule = require("./config");
sinon.stub(configModule, "getConfig").returns(require('./e2e.config'));

This is not a tested code, but I a bit certain that this pattern of thought should work.

like image 133
Akinjiola Toni Avatar answered Jan 05 '23 14:01

Akinjiola Toni