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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With