Permalink
Browse files

Update loadFile - allow passing globals, add some unit tests

  • Loading branch information...
1 parent 1c407de commit c3198619ceeee09c29febecebe08f5cfc6686905 @vojtajina committed Mar 12, 2012
Showing with 48 additions and 2 deletions.
  1. +1 −1 README.md
  2. +7 −1 lib/util.js
  3. +3 −0 test/fixtures/other.js
  4. +6 −0 test/fixtures/some.js
  5. +31 −0 test/util.spec.coffee
View
@@ -129,7 +129,7 @@ I will keep adding more and of course if anyone wants to help - pull requests ar
- http.ServerRequest
-### loadFile(path [, mocks])
+### loadFile(path [, mocks] [, globals])
### predictableNextTick(fn)
### predictableNextTick.pattern
View
@@ -64,8 +64,9 @@ 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 ()
*/
-var loadFile = function(filePath, mocks) {
+var loadFile = function(filePath, mocks, globals) {
mocks = mocks || {};
// this is necessary to allow relative path modules within loaded file
@@ -82,13 +83,18 @@ var loadFile = function(filePath, mocks) {
},
__dirname: path.dirname(filePath),
__filename: filePath,
+ process: process,
console: console,
exports: exports,
module: {
exports: exports
}
};
+ Object.getOwnPropertyNames(globals || {}).forEach(function(name) {
+ context[name] = globals[name];
+ });
+
vm.runInNewContext(fs.readFileSync(filePath), context);
return context;
};
@@ -0,0 +1,3 @@
+// A fake module for testing util.loadFile()
+
+exports.id = 'LOCAL_MODULE';
@@ -0,0 +1,6 @@
+// A fake module for testing util.loadFile()
+
+var privateNumber = 100;
+var privateFs = require('fs');
+var privateLocalModule = require('./other');
+var privateConsole = console;
View
@@ -97,3 +97,34 @@ describe 'mock-util', ->
waitsFor (-> callback.callCount), 'later added fn to be called', 100
waitsFor (-> anotherCallback.callCount), 'another later added fn to be called', 100
+
+
+ #============================================================================
+ # util.loadFile()
+ #============================================================================
+ describe 'loadFile', ->
+ loadFile = util.loadFile
+ fixturePath = __dirname + '/fixtures/some.js'
+
+ it 'should load file with access to private state', ->
+ module = loadFile fixturePath
+ expect(module.privateNumber).toBe 100
+
+
+ it 'should inject mocks', ->
+ fsMock = {}
+ module = loadFile fixturePath, {fs: fsMock}
+ expect(module.privateFs).toBe fsMock
+
+
+ it 'should load local modules', ->
+ module = loadFile fixturePath
+ expect(module.privateLocalModule).toBeDefined()
+ expect(module.privateLocalModule.id).toBe 'LOCAL_MODULE'
+
+
+ it 'should inject globals', ->
+ fakeConsole = {}
+ module = loadFile fixturePath, {}, {console: fakeConsole}
+ expect(module.privateConsole).toBe fakeConsole
+

0 comments on commit c319861

Please sign in to comment.