1 | var Module = require('module')
|
2 | , dirname = require('path').dirname
|
3 | , join = require('path').join
|
4 | , callerId = require('caller-id')
|
5 | , originalLoader = Module._load
|
6 | , intercept = {}
|
7 | ;
|
8 |
|
9 | Module._load = function(request, parent) {
|
10 | var fullFilePath = Module._resolveFilename(request, parent);
|
11 |
|
12 | if (!intercept.hasOwnProperty(fullFilePath)) {
|
13 | return originalLoader.apply(this, arguments);
|
14 | }
|
15 |
|
16 | return intercept[fullFilePath];
|
17 | };
|
18 |
|
19 | function startMocking(path, mockExport) {
|
20 | var calledFrom = callerId.getData().filePath;
|
21 |
|
22 | if (typeof mockExport === 'string') {
|
23 | mockExport = require(getFullPath(mockExport, calledFrom));
|
24 | }
|
25 |
|
26 | intercept[getFullPath(path, calledFrom)] = mockExport;
|
27 | }
|
28 |
|
29 | function stopMocking(path) {
|
30 | var calledFrom = callerId.getData().filePath;
|
31 | delete intercept[getFullPath(path, calledFrom)];
|
32 | }
|
33 |
|
34 | function getFullPath(path, calledFrom) {
|
35 | var needsFullPath = true
|
36 | , resolvedPath
|
37 | , isExternal
|
38 | ;
|
39 |
|
40 | try {
|
41 | resolvedPath = require.resolve(path);
|
42 | isExternal = resolvedPath.indexOf('/node_modules/') !== -1;
|
43 |
|
44 | needsFullPath = resolvedPath !== path && !isExternal;
|
45 |
|
46 | if (isExternal) {
|
47 | path = resolvedPath;
|
48 | }
|
49 | } catch(e) { }
|
50 |
|
51 | if (needsFullPath) {
|
52 | path = join(dirname(calledFrom), path);
|
53 | path = Module._resolveFilename(path);
|
54 | }
|
55 |
|
56 | return path;
|
57 | }
|
58 |
|
59 | module.exports = startMocking;
|
60 | module.exports.stop = stopMocking;
|