1+ "use strict" ; // run code in ES5 strict mode
2+
3+ var Module = require ( "module" ) ,
4+ nodeWrapper0 = Module . wrapper [ 0 ] , // caching original wrapper
5+ nodeWrapper1 = Module . wrapper [ 1 ] ,
6+ getLeakingSrc = require ( "./getLeakingSrc.js" ) ,
7+ getMonkeyPatchSrc = require ( "./getMonkeyPatchSrc.js" ) ;
8+
9+ function restoreOriginalWrappers ( ) {
10+ Module . wrapper [ 0 ] = nodeWrapper0 ;
11+ Module . wrapper [ 1 ] = nodeWrapper1 ;
12+ }
13+
14+ function trick ( parentModule , filename , mocks , injections , leaks , cache ) {
15+ var testModule ,
16+ nodeRequire ;
17+
18+ function requireTrick ( path ) {
19+ restoreOriginalWrappers ( ) ; // we need to restore the wrappers now so we don't influence other modules
20+
21+ if ( mocks && mocks . hasOwnProperty ( path ) ) {
22+ return mocks [ path ] ;
23+ } else {
24+ return nodeRequire . call ( testModule , path ) ; // node's require only works when "this" points to the module
25+ }
26+ }
27+
28+ // Checking params
29+ if ( typeof filename !== "string" ) {
30+ throw new TypeError ( "Filename must be a string" ) ;
31+ }
32+
33+ // Init vars
34+ filename = Module . _resolveFilename ( filename , parentModule ) ; // resolve full filename relative to the parent module
35+ testModule = new Module ( filename , parentModule ) ;
36+ nodeRequire = testModule . require ; // caching original node require
37+
38+ // Prepare module for injection
39+ if ( typeof injections === "object" ) {
40+ Module . wrapper [ 0 ] = nodeWrapper0 + getMonkeyPatchSrc ( injections ) ;
41+ } else if ( typeof injections === "string" ) {
42+ Module . wrapper [ 0 ] = nodeWrapper0 + injections ;
43+ }
44+
45+ // Prepare module for leaking private vars
46+ if ( Array . isArray ( leaks ) ) {
47+ Module . wrapper [ 1 ] = getLeakingSrc ( leaks ) + nodeWrapper1 ;
48+ }
49+
50+ // Mocking module.require-function
51+ testModule . require = requireTrick ;
52+ // Loading module
53+ testModule . load ( testModule . id ) ;
54+
55+ if ( cache ) {
56+ require . cache [ filename ] = testModule ;
57+ }
58+
59+ restoreOriginalWrappers ( ) ; // this is only necessary if nothing has been required within the module
60+
61+ return testModule . exports ;
62+ }
63+
64+ module . exports = trick ;
0 commit comments