I have a very strange behaviour (from my point of view):
I cannot write any file when I make my unit tests using mocha (I can create the files but nothing is written to them).
As an example I have this piece of code:
console.log('The beginning');
var fs = require('fs');
var writableStream = fs.createWriteStream("./testOuputFile.txt");
function callback(s){
console.log('callback', s);
}
writableStream.on("error", function(err) {
console.log("ERROR");
done(err);
});
writableStream.on("close", function(ex) {
console.log("CLOSED");
done();
});
writableStream.on("finish", function(ex) {
console.log("ENDED");
done();
});
writableStream.on("open", function(fd) {
console.log("OPENED:"+fd);
});
if(typeof callback === "undefined"){
callback = function(s){console.log(s);};
}
var cbCalled = false;
function done(err) {
if (!cbCalled) {
callback(err);
cbCalled = true;
}
}
writableStream.write('Something');
writableStream.end();
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
console.log('The end');
Copying this code into a file named run.js and run 'node run.js' will output:
The beginning
The end
OPENED:11
ENDED
callback undefined
CLOSED
It's saved!
I obtain two nice files containing some text: testOutputFile.txt and message.txt
Doing the same into a file named test/test.js and run 'mocha' will output:
The beginning
The end
0 tests complete (0 ms)
And I obtain two empty files (zero bytes): testOutputFile.txt and message.txt
Is it normal ?
Is there something to tune in mocha to make this work ?
Almost certainly you forgot to include the done callback in your describe/it function argument list so mocha thinks your test is synchronous and it doesn't have any way to know when your IO is done, so as soon as your function returns, mocha ends the process. But as @BenjaminGruenbaum points out, you omitted the interesting part of the code, so post the full code and we'll confirm.