Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 626
Rookee Avatar asked Apr 06 '14 08:04

Rookee


People also ask

Is it possible to write tests in node without an external library?

If you've ever written tests for a Node. js application, chances are you used an external library. However, you don't need a library to run unit tests in Javascript.

Which module is used for testing a node application?

The assert module. The basis for most Node unit testing is the built-in assert module, which tests a condition and, if the condition isn't met, throws an error. Node's assert module is used by many third-party testing frameworks. Even without a testing framework, you can do useful testing with it.

What's the difference between module exports and exports?

When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way.

What can be exported from a module?

The export statement is used in Javascript modules to export functions, objects, or primitive values from one module so that they can be used in other programs (using the 'import' statement). A module encapsulates related code into a single unit of code. All functions related to a single module are contained in a file.


1 Answers

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.

like image 162
thefourtheye Avatar answered Sep 22 '22 00:09

thefourtheye