How to access and test an internal (non-exports) function in a node.js module?

后端 未结 8 1980
别跟我提以往
别跟我提以往 2020-12-12 09:31

I\'m trying to figure out on how to test internal (i.e. not exported) functions in nodejs (preferably with mocha or jasmine). And i have no idea!

Let say I have a mo

8条回答
  •  眼角桃花
    2020-12-12 10:15

    EDIT:

    Loading a module using vm can cause unexpected behavior (e.g. the instanceof operator no longer works with objects that are created in such a module because the global prototypes are different from those used in module loaded normally with require). I no longer use the below technique and instead use the rewire module. It works wonderfully. Here's my original answer:

    Elaborating on srosh's answer...

    It feels a bit hacky, but I wrote a simple "test_utils.js" module that should allow you to do what you want without having conditional exports in your application modules:

    var Script = require('vm').Script,
        fs     = require('fs'),
        path   = require('path'),
        mod    = require('module');
    
    exports.expose = function(filePath) {
      filePath = path.resolve(__dirname, filePath);
      var src = fs.readFileSync(filePath, 'utf8');
      var context = {
        parent: module.parent, paths: module.paths, 
        console: console, exports: {}};
      context.module = context;
      context.require = function (file){
        return mod.prototype.require.call(context, file);};
      (new Script(src)).runInNewContext(context);
      return context;};
    

    There are some more things that are included in a node module's gobal module object that might also need to go into the context object above, but this is the minimum set that I need for it to work.

    Here's an example using mocha BDD:

    var util   = require('./test_utils.js'),
        assert = require('assert');
    
    var appModule = util.expose('/path/to/module/modName.js');
    
    describe('appModule', function(){
      it('should test notExposed', function(){
        assert.equal(6, appModule.notExported(3));
      });
    });
    

提交回复
热议问题