I have a util that I want to test:
var util = function(data) {
.....
console.log('msg');
....
return true
}
My test.js
describe('util', function () {
it('should ...', function () {
expect(util({})).to.be.true;
});
});
How can I avoid 'msg' output during the test without changing the util?
2 Answers 2
I don't know much about mocha but would this work?
describe('util', function () {
it('should ...', function () {
var logg = console.log;
console.log = function(m){};
expect(util({})).to.be.true;
console.log = logg;
});
});
1 Comment
console = {log: function(){}, info: ...} :)Preferably you would use something like winston, otherwise you will have to use conditionals.
I have a small utility for that, first I will show how to use it then I will show the code;
ifEnvironmentIs('production').log('msg'); //Prints message only in production
ifEnvironmentIs('test').or('staging').log('msg'); //only in test and staging
And the code is like this
function environmentIs(desired) {
if(!Array.isArray(desired)) {
desired = [desired];
}
return desired.indexOf(NODE_ENV) > -1;
}
function ifEnvironmentIs(desired) {
desired = [desired];
var that = {};
that.then = function(fn) {
if(environmentIs(desired)) {
fn();
}
return that;
};
that.or = function(env) {
desired.push(env);
return that;
},
that.otherwise = function(fn){
if(!environmentIs(desired)) {
fn();
}
return that;
};
that.log = function(text) {
if(environmentIs(desired)) {
console.log(text);
}
return that;
};
return that;
}
It works based on environment variables, which is the best way to differentiate between your running environments, like TEST, PRODUCTION and DEVELOPMENT
You can use the code provided also to execute function conditionally by using the .then and .otherwise functions.
You can extend this code to include your custom logging method (instead of console)
winstonshould be more suitable.