NodeJS simple mocking
Example:
mySuperModule.js:
var myAnotherModule = require('myAnotherModule');
var logger = require(__dirname + "/../config/logging");
exports.func = function func(arg) {
logger.log(myAnotherModule.foo());
return new Buffer(arg + myAnotherModule.foo() + arg);
}
test_mySuperModule.js:
var mock = require("mock-all");
var fsMock = {
readFileSync: function() {
return "";
}
};
myAnotherModuleMock = {
foo: function () {
return "bar";
}
}
var mocks = {
fs: fsMock,
myAnotherModule: myAnotherModuleMock,
"/../config/logging": console
};
var globals = {
// can override global __dirname in mySuperModule.js
__dirname: __dirname,
Buffer: Buffer
};
var mockedModule = mock("#{__dirname}/../build/mySuperModule.js", mocks, globals);
var buf = mockedModule.func("str");
assert.ok(buffer.isBuffer(buf), "Test failed!");
You can mock any variable after create mocked module:
mockedModule.__setMock__("fs", {writeFile: function(f, d, cb) {cb(null)}});
And restore mocked variable with setMock:
mockedModule.__restoreAll__();