Mocha Monitor Application Output
mocha.js, node.js
Solution
`process.stdout` is never going to emit `'data'` events because it's not a readable stream. You can read all about that in the node stream documentation, if you're curious.
As far as I know, the simplest way to hook or capture `process.stdout` or `process.stderr` is to replace `process.stdout.write` with a function that does what you want. Super hacky, I know, but in a testing scenario you can use before and after hooks to make sure it gets unhooked, so it's more or less harmless. Since it writes to the underlying stream anyway, it's not the end of the world if you don't unhook it anyway.
function captureStream(stream){
var oldWrite = stream.write;
var buf = '';
stream.write = function(chunk, encoding, callback){
buf += chunk.toString(); // chunk is a String or Buffer
oldWrite.apply(stream, arguments);
}
return {
unhook: function unhook(){
stream.write = oldWrite;
},
captured: function(){
return buf;
}
};
}
You can use it in mocha tests like this:
describe('console.log', function(){
var hook;
beforeEach(function(){
hook = captureStream(process.stdout);
});
afterEach(function(){
hook.unhook();
});
it('prints the argument', function(){
console.log('hi');
assert.equal(hook.captured(),'hi\n');
});
});
Here's a caveat: mocha reporters print to the standard output. They do not, as far as I know, do so while example (`it('...',function(){})`) functions are running, but you may run into trouble if your example functions are asynchronous. I'll see if I can find more out about this.
Problem
I'm building a logging module for my web app in `nodejs`. I'd like to be able to test using `mocha` that my module outputs the correct messages to the `terminal`. I have been looking around but haven't found any obvious solutions to check this. I have found ``` process.stdout.on('data', function (){}) ``` but haven't been able to get this to work. does anybody have any advice?