@@ -26,20 +26,43 @@ Installation
26
26
Examples
27
27
--------
28
28
29
+ Imagine you want to test this module:
30
+
29
31
``` javascript
30
- var rewire= require (" rewire" );
32
+ // lib/myModule.js
33
+
34
+ // With rewire you can change all these variables
35
+ var fs= require (" fs" ),
36
+ http= require (" http" ),
37
+ someOtherVar= " hi" ,
38
+ myPrivateVar= 1 ;
39
+
40
+ function readSomethingFromFileSystem (cb ) {
41
+ // But no scoped variables
42
+ var path= " /somewhere/on/the/disk" ;
43
+
44
+ console .log (" Reading from file system ..." );
45
+ fs .readFile (path," utf8" , cb);
46
+ }
47
+
48
+ exports .readSomethingFromFileSystem = readSomethingFromFileSystem;
49
+ ```
50
+
51
+ Now within your test module:
31
52
53
+ ``` javascript
54
+ // test/myModule.test.js
55
+
56
+ var rewire= require (" rewire" );
32
57
33
58
// rewire acts exactly like require.
34
59
var myModule= rewire (" ../lib/myModule.js" );
35
60
36
-
37
61
// Just with one difference:
38
62
// Your module will now export a special setter and getter for private variables.
39
63
myModule .__set__ (" myPrivateVar" ,123 );
40
64
myModule .__get__ (" myPrivateVar" );// = 123
41
65
42
-
43
66
// This allows you to mock almost everything within the module e.g. the fs-module.
44
67
// Just pass the variable name as first parameter and your mock as second.
45
68
myModule .__set__ (" fs" , {
@@ -51,15 +74,13 @@ myModule.readSomethingFromFileSystem(function (err, data) {
51
74
console .log (data);// = Success!
52
75
});
53
76
54
-
55
77
// You can set different variables with one call.
56
78
myModule .__set__ ({
57
79
fs: fsMock,
58
80
http: httpMock,
59
81
someOtherVar: " hello"
60
82
});
61
83
62
-
63
84
// You may also override globals. These changes are only within the module, so
64
85
// you don't have to be concerned that other modules are influenced by your mock.
65
86
myModule .__set__ ({
@@ -71,7 +92,6 @@ myModule.__set__({
71
92
}
72
93
});
73
94
74
-
75
95
// But be careful, if you do something like this you'll change your global
76
96
// console instance.
77
97
myModule .__set__ (" console.log" ,function () {/* be quiet*/ });
@@ -145,4 +165,4 @@ var webpackOptions = {
145
165
require (" rewire" ).bundlers .webpack (webpackOptions);
146
166
147
167
webpack (" entry.js" , webpackOptions,function () {});
148
- ```
168
+ ```