If the module functions call the module with other functions directly (i.e., using links that are local to the module), it is impossible to intercept these calls from the outside. However, if you change your module so that the functions inside it call the functions of the module as well as outside it, then you can intercept these calls.
Here is an example that will allow you:
define([], function () { "use strict"; var foo = function(){ return exports.bar(); }; var bar = function(){ return "original"; }; var exports = { foo: foo, bar: bar }; return exports; });
The key is that foo goes through exports to access the bar , and not to call it directly.
I gave a runnable example here . The spec/main.spec.js contains:
expect(moduleA.foo()).toEqual("original"); spyOn(moduleA, "bar").andReturn("patched"); expect(moduleA.foo()).toEqual("patched");
You will notice that bar is a fixed function, but foo affects the correction.
In addition, in order to avoid constant contamination of exports with test code, I sometimes did an environmental check to determine if the module was running in a test environment and exported the functions necessary for testing only in test mode. Here is an example of the actual code that I wrote:
var options = module.config(); var test = options && options.test; [...] // For testing only if (test) { exports.__test = { $modal: $modal, reset: _reset, is_terminating: _is_terminating }; }
If the requirejs configuration configures my module (using config ) to have the test option set to true, then the export additionally contains the __test symbol, which contains some additional elements that I want to export when I test the module. Otherwise, these characters are not available.
Edit: if you are concerned about the first method described above that you need to prefix all calls to internal functions with exports , you can do something like this:
define(["module"], function (module) { "use strict"; var debug = module.config().debug; var exports = {}; var _dynamic = (debug ? function (name, f) { exports[name] = f; return function () {
When the RequireJS configuration configures the module above so that debug is true, it exports the functions wrapped in _dynamic and provides local characters that allow them to be referenced without going through exports . If debug is false, then the function is not exported or wrapped. I updated the example to show this method. This is moduleB in the example.