1 | rewire
|
2 | ======
|
3 | **Easy monkey-patching for node.js unit tests**
|
4 |
|
5 | [![](https://img.shields.io/npm/v/rewire.svg)](https://www.npmjs.com/package/rewire)
|
6 | [![](https://img.shields.io/npm/dm/rewire.svg)](https://www.npmjs.com/package/rewire)
|
7 | [![Coverage Status](https://img.shields.io/coveralls/jhnns/rewire.svg)](https://coveralls.io/r/jhnns/rewire?branch=master)
|
8 |
|
9 | rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may
|
10 |
|
11 | - inject mocks for other modules or globals like `process`
|
12 | - inspect private variables
|
13 | - override variables within the module.
|
14 |
|
15 | **Please note:** The current version of rewire is only compatible with CommonJS modules. See [Limitations](https://github.com/jhnns/rewire#limitations).
|
16 |
|
17 | <br>
|
18 |
|
19 | Installation
|
20 | ------------
|
21 |
|
22 | `npm install rewire`
|
23 |
|
24 | <br />
|
25 |
|
26 | Introduction
|
27 | ------------
|
28 |
|
29 | Imagine you want to test this module:
|
30 |
|
31 | ```javascript
|
32 | // lib/myModule.js
|
33 | // With rewire you can change all these variables
|
34 | var fs = require("fs"),
|
35 | path = "/somewhere/on/the/disk";
|
36 |
|
37 | function readSomethingFromFileSystem(cb) {
|
38 | console.log("Reading from file system ...");
|
39 | fs.readFile(path, "utf8", cb);
|
40 | }
|
41 |
|
42 | exports.readSomethingFromFileSystem = readSomethingFromFileSystem;
|
43 | ```
|
44 |
|
45 | Now within your test module:
|
46 |
|
47 | ```javascript
|
48 | // test/myModule.test.js
|
49 | var rewire = require("rewire");
|
50 |
|
51 | var myModule = rewire("../lib/myModule.js");
|
52 | ```
|
53 |
|
54 | rewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.
|
55 |
|
56 | ```javascript
|
57 | myModule.__set__("path", "/dev/null");
|
58 | myModule.__get__("path"); // = '/dev/null'
|
59 | ```
|
60 |
|
61 | This allows you to mock everything in the top-level scope of the module, like the fs module for example. Just pass the variable name as first parameter and your mock as second.
|
62 |
|
63 | ```javascript
|
64 | var fsMock = {
|
65 | readFile: function (path, encoding, cb) {
|
66 | expect(path).to.equal("/somewhere/on/the/disk");
|
67 | cb(null, "Success!");
|
68 | }
|
69 | };
|
70 | myModule.__set__("fs", fsMock);
|
71 |
|
72 | myModule.readSomethingFromFileSystem(function (err, data) {
|
73 | console.log(data); // = Success!
|
74 | });
|
75 | ```
|
76 |
|
77 | You can also set multiple variables with one call.
|
78 |
|
79 | ```javascript
|
80 | myModule.__set__({
|
81 | fs: fsMock,
|
82 | path: "/dev/null"
|
83 | });
|
84 | ```
|
85 |
|
86 | You may also override globals. These changes are only within the module, so you don't have to be concerned that other modules are influenced by your mock.
|
87 |
|
88 | ```javascript
|
89 | myModule.__set__({
|
90 | console: {
|
91 | log: function () { /* be quiet */ }
|
92 | },
|
93 | process: {
|
94 | argv: ["testArg1", "testArg2"]
|
95 | }
|
96 | });
|
97 | ```
|
98 |
|
99 | `__set__` returns a function which reverts the changes introduced by this particular `__set__` call
|
100 |
|
101 | ```javascript
|
102 | var revert = myModule.__set__("port", 3000);
|
103 |
|
104 | // port is now 3000
|
105 | revert();
|
106 | // port is now the previous value
|
107 | ```
|
108 |
|
109 | For your convenience you can also use the `__with__` method which reverts the given changes after it finished.
|
110 |
|
111 | ```javascript
|
112 | myModule.__with__({
|
113 | port: 3000
|
114 | })(function () {
|
115 | // within this function port is 3000
|
116 | });
|
117 | // now port is the previous value again
|
118 | ```
|
119 |
|
120 | The `__with__` method is also aware of promises. If a thenable is returned all changes stay until the promise has either been resolved or rejected.
|
121 |
|
122 | ```javascript
|
123 | myModule.__with__({
|
124 | port: 3000
|
125 | })(function () {
|
126 | return new Promise(...);
|
127 | }).then(function () {
|
128 | // now port is the previous value again
|
129 | });
|
130 | // port is still 3000 here because the promise hasn't been resolved yet
|
131 | ```
|
132 |
|
133 | <br />
|
134 |
|
135 | Limitations
|
136 | -----------
|
137 |
|
138 | **Babel's ES module emulation**<br>
|
139 | During the transpilation step from ESM to CJS modules, Babel renames internal variables. Rewire will not work in these cases (see [#62](https://github.com/jhnns/rewire/issues/62)). Other Babel transforms, however, should be fine. Another solution might be switching to [babel-plugin-rewire](https://github.com/speedskater/babel-plugin-rewire).
|
140 |
|
141 | **Variables inside functions**<br>
|
142 | Variables inside functions can not be changed by rewire. This is constrained by the language.
|
143 |
|
144 | ```javascript
|
145 | // myModule.js
|
146 | (function () {
|
147 | // Can't be changed by rewire
|
148 | var someVariable;
|
149 | })()
|
150 | ```
|
151 |
|
152 | **Modules that export primitives**<br>
|
153 | rewire is not able to attach the `__set__`- and `__get__`-method if your module is just exporting a primitive. Rewiring does not work in this case.
|
154 |
|
155 | ```javascript
|
156 | // Will throw an error if it's loaded with rewire()
|
157 | module.exports = 2;
|
158 | ```
|
159 |
|
160 | **Globals with invalid variable names**<br>
|
161 | rewire imports global variables into the local scope by prepending a list of `var` declarations:
|
162 |
|
163 | ```javascript
|
164 | var someGlobalVar = global.someGlobalVar;
|
165 | ```
|
166 |
|
167 | If `someGlobalVar` is not a valid variable name, rewire just ignores it. **In this case you're not able to override the global variable locally**.
|
168 |
|
169 | **Special globals**<br>
|
170 | Please be aware that you can't rewire `eval()` or the global object itself.
|
171 |
|
172 |
|
173 | <br />
|
174 |
|
175 | API
|
176 | ---
|
177 |
|
178 | ### rewire(filename: String): rewiredModule
|
179 |
|
180 | Returns a rewired version of the module found at `filename`. Use `rewire()` exactly like `require()`.
|
181 |
|
182 | ### rewiredModule.__set__(name: String, value: *): Function
|
183 |
|
184 | Sets the internal variable `name` to the given `value`. Returns a function which can be called to revert the change.
|
185 |
|
186 | ### rewiredModule.__set__(obj: Object): Function
|
187 |
|
188 | Takes all enumerable keys of `obj` as variable names and sets the values respectively. Returns a function which can be called to revert the change.
|
189 |
|
190 | ### rewiredModule.__get__(name: String): *
|
191 |
|
192 | Returns the private variable with the given `name`.
|
193 |
|
194 | ### rewiredModule.__with__(obj: Object): Function<callback: Function>
|
195 |
|
196 | Returns a function which - when being called - sets `obj`, executes the given `callback` and reverts `obj`. If `callback` returns a promise, `obj` is only reverted after the promise has been resolved or rejected. For your convenience the returned function passes the received promise through.
|
197 |
|
198 | <br />
|
199 |
|
200 | Caveats
|
201 | -------
|
202 |
|
203 | **Difference to require()**<br>
|
204 | Every call of rewire() executes the module again and returns a fresh instance.
|
205 |
|
206 | ```javascript
|
207 | rewire("./myModule.js") === rewire("./myModule.js"); // = false
|
208 | ```
|
209 |
|
210 | This can especially be a problem if the module is not idempotent [like mongoose models](https://github.com/jhnns/rewire/issues/27).
|
211 |
|
212 | **Globals are imported into the module's scope at the time of rewiring**<br>
|
213 | Since rewire imports all gobals into the module's scope at the time of rewiring, property changes on the `global` object after that are not recognized anymore. This is a [problem when using sinon's fake timers *after* you've called `rewire()`](http://stackoverflow.com/questions/34885024/when-using-rewire-and-sinon-faketimer-order-matters/36025128).
|
214 |
|
215 | **Dot notation**<br>
|
216 | Although it is possible to use dot notation when calling `__set__`, it is strongly discouraged in most cases. For instance, writing `myModule.__set__("console.log", fn)` is effectively the same as just writing `console.log = fn`. It would be better to write:
|
217 |
|
218 | ```javascript
|
219 | myModule.__set__("console", {
|
220 | log: function () {}
|
221 | });
|
222 | ```
|
223 |
|
224 | This replaces `console` just inside `myModule`. That is, because rewire is using `eval()` to turn the key expression into an assignment. Hence, calling `myModule.__set__("console.log", fn)` modifies the `log` function on the *global* `console` object.
|
225 |
|
226 | <br />
|
227 |
|
228 | webpack
|
229 | -------
|
230 | See [rewire-webpack](https://github.com/jhnns/rewire-webpack)
|
231 |
|
232 | <br />
|
233 |
|
234 | ## License
|
235 |
|
236 | MIT
|