Permalink
Browse files

Allow injecting mocks into nested deps

  • Loading branch information...
1 parent ba97dc9 commit c554265dae155529a93bc7d71075a73e1d3de900 @vojtajina committed Sep 23, 2012
Showing with 35 additions and 8 deletions.
  1. +24 −8 lib/util.js
  2. +1 −0 test/fixtures/other.js
  3. +10 −0 test/util.spec.coffee
View
@@ -74,23 +74,39 @@ predictableNextTick.pattern = [0];
* @param {string} path Absolute path to module (file to load)
* @param {Object=} mocks Hash of mocked dependencies
* @param {Object=} globals Hash of globals ()
+ * @param {boolean} mockNested If true, mock even nested requires. Default to false
*/
-var loadFile = function(filePath, mocks, globals) {
+var loadFile = function(filePath, mocks, globals, mockNested) {
mocks = mocks || {};
+ globals = globals || {};
+
filePath = path.normalize(filePath);
- // this is necessary to allow relative path modules within loaded file
- // i.e. requiring ./some inside file /a/b.js needs to be resolved to /a/some
- var resolveModule = function(module) {
- if (module.charAt(0) !== '.') return module;
- return path.resolve(path.dirname(filePath), module);
- };
+ if (filePath.substr(-3) !== '.js') {
+ filePath += '.js';
+ }
var exports = {};
var context = {
require: function(name) {
// TODO(vojta): solve loading "localy installed" modules
- return mocks[name] || require(resolveModule(name));
+ if (mocks.hasOwnProperty(name)) {
+ return mocks[name];
+ }
+
+ // this is necessary to allow relative path modules within loaded file
+ // i.e. requiring ./some inside file /a/b.js needs to be resolved to /a/some
+ if (name.charAt(0) !== '.') {
+ return require(name);
+ }
+
+ var absolutePath = path.resolve(path.dirname(filePath), name);
+
+ if (mockNested) {
+ return loadFile(absolutePath, mocks, globals, mockNested).module.exports;
+ }
+
+ return require(absolutePath);
},
__dirname: path.dirname(filePath),
__filename: filePath,
View
@@ -1,3 +1,4 @@
// A fake module for testing util.loadFile()
exports.id = 'LOCAL_MODULE';
+exports.fs = require('fs');
View
@@ -170,3 +170,13 @@ describe 'mock-util', ->
module = loadFile fixturePath, {}, {console: fakeConsole}
expect(module.privateConsole).toBe fakeConsole
+
+ it 'should inject mocks into nested modules', ->
+ fsMock = {}
+
+ # /fixtures/some.js requires /fixtures/other.js
+ # /fixtures/other.js requires fs
+ module = loadFile fixturePath, {fs: fsMock}, {}, true
+
+ expect(module.privateLocalModule.fs).toBe fsMock
+

0 comments on commit c554265

Please sign in to comment.