7

Here is a normal node module. With some functions that are not all exported, but they needed 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
}

Anybody knows how to test foo3? Normally I test modules with node-sandboxed-module. But there is only possible to mock given things for the module, but I can not change the scope of methods.

Sample for 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 help!

Rookee
  • 611
  • 2
  • 7
  • 17
  • Just also export foo3, prefixing it with a underscore denotes that it is a private function, for example `_foo3: foo3`. – Zoey Mertes Apr 06 '14 at 08:31
  • possible duplicate of [How to access and test an internal (non-exports) function in a node.js module?](http://stackoverflow.com/questions/14874208/how-to-access-and-test-an-internal-non-exports-function-in-a-node-js-module) – waterproof Mar 26 '15 at 16:33

2 Answers2

10

You cannot change the scoping rules of the language. But you can get around this. You can export an environment variable, and if the variable exists, you can export foo3 as well. Like this

module.exports = {
  foo1: foo1,
  foo2: foo2
}

if (process.env.TESTING) {
    module.exports.foo3 = foo3;
}

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

Also, using _ in the function's name is understood as, the function/variable is for internal use, no external code should be relying on that function/variable and it is subjected to change without any notice.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

I used this, 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
Lyndon S
  • 645
  • 7
  • 6