Mock module which returns a function in node.js

Viewed 996

We have some node.js code we want to test. These are modules which return a function (module.exports = function(){...}). Inside the function some other modules are required. Now we want to mock these modules. See example below:

// userRepo.js
module.exports = function(connection) {
    // init the repo
    var repo = DB.connect(connection);    

    // add validation function
    repo.validate = function(data, cb) {
        // do validation stuff
        cb(error, result);
    };

    return repo;
};

// userController.js
module.exports = function(config) {
    var repo = require('userRepo.js')(config.connectionStringToUserDB)
    var pub = {};

    pub.create = function(data, cb) {
        repo.validate(data, function(err, res) {
            // do some stuff
        };
    };

    return pub;
}

// the test
var sut = require('userController.js')(anyConfig);

sut.create({}, function(err, res) {
    // do some assertions here
};

So in the test we want to mock/stub the function repo.validate(). But until now we found no way doing this. All the node.js mocking frameworks/libs we tested can mock a module and then you can override the exports. But in our case the module returns a function and in the controller the repo is already instantiated.

I hope my explanations are understandable :-)

Thanks for any help.

1 Answers
Related