This is especially nice because you don't need to add any special if statements to the module code you just load your module under test using rewire instead of require.
// file: test-stats-rewire.js
var rewire = require('rewire');
var assert = require('assert');
var stats = rewire('./stats');
// leak private method sum for testing
var sum = stats.__get__('sum');
assert.equal(sum([1]), 1);
assert.equal(sum([1, 2, 3]), 6);
In the example given, the sum function could be its own module that you require into the stats module. That way you could test them independently, and the stats module could simply expose its own appropriate methods.
This has the added benefit of making the sum function reusable.
Personally I prefer this approach to introducing environmental concerns into your code.
I'm also not sure I buy the assertion that all code you would want to test is code you would want to export publicly. Do you have any reasoning to support that idea?
All code you would want to test (or, even, to have exist) is either code that is in publicly exported functions or code whose pathways can all be exercised via interaction with the publicly exported interfaces, since code pathways that are neither in publicly exported functions nor reachable through publicly exported functions is dead code.
If its not testable via the public interface, it shouldn't exist.
This probably isn't categorically true, but it's served me pretty well.
+1 to that.
When you pull out complex code like this into another module, how do you specify that the new module is actually private to the old module?
https://github.com/ModuleLoader/es6-module-loader
It can deal with both AMD and CommonJS modules, as well as es6 import/export. It does not need traceur and will work with today's JS. And is built upon the standards based System.js which basically provide loader hooks for node, JS, and even Web Components if they so desire.
It is sure nice to get rid of the forrest of <script> tags and not be concerned about order of dependencies.
http://lostechies.com/derickbailey/2014/01/03/semantics-modu...