Mock module that returns a function in node.js

We have the node.js code we want to test. These are modules that return a function (module.exports = function () {...}). Inside the function, some other modules are required. Now we want to mock these modules. See the 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 / drown out the repo.validate () function. But so far we have not found any way to do this. All node.js mocking frameworks / libs that we tested can mock the module, and then you can override the export. But in our case, the module returns a function, and in the controller the repo is already created.

I hope my explanations are clear :-)

Thanks for any help.

+4
1

, , - . , repo userRepo.js. , , . .

// userRepo.js
module.exports = function(connection) {

    var api = {}, repo;

    api.setRepo = function(r) {
      repo = r;
    }
    api.getRepo = function() {
      return repo;
    }
    api.init = function() {

      // init the repo
      repo = repo || DB.connect(connection);

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

    }

    return api;
};

, , varialbe repo . , , , userRepo.js

var userRepo = require("./userRepo.js")(connection)

var userRepo = require("./userRepo.js")(connection).init();

. :

var userRepo = require("./userRepo.js")(connection).setRepo(customRepo).init();

var userRepo = require("./userRepo.js")(connection);
var repo = userRepo.getRepo();
repo.validate = function() {
   // custom stuff here
}
userRepo.init();

, : -, : " ?".

+2

All Articles