UNPKG

1.42 kBJavaScriptView Raw
1var Module = require('module')
2 , dirname = require('path').dirname
3 , join = require('path').join
4 , originalLoader = Module._load
5 , intercept = {}
6 ;
7
8Module._load = function(request, parent) {
9 var fullFilePath = Module._resolveFilename(request, parent);
10
11 if (!intercept.hasOwnProperty(fullFilePath)) {
12 return originalLoader.apply(this, arguments);
13 }
14
15 return intercept[fullFilePath];
16};
17
18function startMocking(path, mockExport) {
19 if (typeof mockExport === 'string') {
20 mockExport = require(getFullPath(mockExport));
21 }
22
23 intercept[getFullPath(path)] = mockExport;
24}
25
26function stopMocking(path) {
27 delete intercept[getFullPath(path)];
28}
29
30function getFullPath(path) {
31 var isNative = false;
32 try {
33 isNative = Module._resolveFilename(path) === path;
34 } catch(e) { }
35
36 if (!isNative) {
37 path = join(dirname(getCallingFile(path)), path);
38 path = Module._resolveFilename(path);
39 }
40
41 return path;
42}
43
44function getCallingFile() {
45 var origPrepareStackTrace = Error.prepareStackTrace
46 , fileName
47 , stack
48 ;
49
50 Error.prepareStackTrace = function (_, stack) { return stack; };
51 stack = new Error().stack;
52 Error.prepareStackTrace = origPrepareStackTrace;
53
54 while (!fileName && stack.length) {
55 fileName = stack.shift().receiver.filename;
56 }
57
58 return fileName;
59}
60
61startMocking.stop = stopMocking;
62module.exports = startMocking;