Testing not exported node module methods

Here is a regular node module. With some features that not all are exported, but they need to test

var foo1 = function () { console.log("Foo1"); } var foo2 = function () { console.log("Foo2"); } var foo3 = function () { console.log("Foo3"); } module.exports = { foo1: foo1, foo2: foo2 } 

Does anyone know how to check foo3? I usually test modules with node-sandboxed-module. But it is only possible to falsify data for a module, but I cannot change the scope of methods.

Sample for a testing module with node-sandboxed-module:

 var SandboxedModule = require('sandboxed-module'); var user = SandboxedModule.require('./user', { requires: {'mysql': {fake: 'mysql module'}}, globals: {myGlobal: 'variable'}, locals: {myLocal: 'other variable'}, }); 

Thanks for the help!

+6
source share
2 answers

You cannot change the language definition rules. But you can get around this. You can export an environment variable, and if the variable exists, you can also export foo3 . Like this

 module.exports = { foo1: foo1, foo2: foo2 } if (process.env.TESTING) { module.exports.foo3 = foo3; } 

So, test foo3 can test foo3 , just like they test other exported functions. But in a production environment, since there will be no TESTING environment variable, foo3 will not be exported.

In addition, when using _ in a function name, the / variable function is understood for internal use, external code should not rely on this function / variable, and it is subject to change without any notice.

+7
source

I used it, it seems to work.

sample.js

 function double(p2) { return p2*2 } module.exports = function(p, p2) { return "Hi "+p+", double "+p2+" = "+double(p2) } 

sample_test.js

 function load(file_name) { global.module = {} const contents = require('fs').readFileSync(file_name, 'utf8'); const vm = require('vm') new vm.Script(contents).runInThisContext(); } load("./sample.js") console.log(global.module.exports("Jim","10")) console.log(double(2)) 

Output

 Hi Jim, double 10 = 20 4 
0
source

All Articles