Rookee Rookee - 1 year ago 65
Node.js Question

Testing not exported node methods of a module

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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download