Reputation: 4615
I am working on an existing node project where the code structure for most of the js files looks something like following.
var mod1 = require("mod1");
var mod2 = require("mod2");
var modn = require("moden");
function func1(data, callback) {
// Do some validation with data etc..
// Use one or more imported modules here
}
function func2(data, callback) {
// Do some validation with data etc..
// Use one or more imported modules here
}
exports.func1 = func1
exports.func2 = func2
How can unit test func1, while not being dependent on the imported modules? How can I mock/stub them? I come from the Java world so I am familiar with the mocking concepts, but here I am not sure how can I mock the globally declared module imports using require.
Currently we are using nodeunit for the unit testing purpose, but it tests very small part of the code.
I am reading about simon.js and testdouble but not sure how to use them to mock the global variables.
Any help/direction is appreciated.
Upvotes: 0
Views: 422
Reputation: 1881
For overriding dependencies during testing I recommend to use in your situation the https://github.com/thlorenz/proxyquire module
For quick exmple I paste example from project github
foo.js:
var path = require('path');
module.exports.extnameAllCaps = function (file) {
return path.extname(file).toUpperCase();
};
module.exports.basenameAllCaps = function (file) {
return path.basename(file).toUpperCase();
}
foo.test.js:
var proxyquire = require('proxyquire')
, assert = require('assert')
, pathStub = { };
// when no overrides are specified, path.extname behaves normally
var foo = proxyquire('./foo', { 'path': pathStub });
assert.equal(foo.extnameAllCaps('file.txt'), '.TXT');
Upvotes: 0