UNPKG

7.42 kBMarkdownView Raw
1rewire
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
9rewire 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
19Installation
20------------
21
22`npm install rewire`
23
24<br />
25
26Introduction
27------------
28
29Imagine you want to test this module:
30
31```javascript
32// lib/myModule.js
33// With rewire you can change all these variables
34var fs = require("fs"),
35 path = "/somewhere/on/the/disk";
36
37function readSomethingFromFileSystem(cb) {
38 console.log("Reading from file system ...");
39 fs.readFile(path, "utf8", cb);
40}
41
42exports.readSomethingFromFileSystem = readSomethingFromFileSystem;
43```
44
45Now within your test module:
46
47```javascript
48// test/myModule.test.js
49var rewire = require("rewire");
50
51var myModule = rewire("../lib/myModule.js");
52```
53
54rewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.
55
56```javascript
57myModule.__set__("path", "/dev/null");
58myModule.__get__("path"); // = '/dev/null'
59```
60
61This 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
64var fsMock = {
65 readFile: function (path, encoding, cb) {
66 expect(path).to.equal("/somewhere/on/the/disk");
67 cb(null, "Success!");
68 }
69};
70myModule.__set__("fs", fsMock);
71
72myModule.readSomethingFromFileSystem(function (err, data) {
73 console.log(data); // = Success!
74});
75```
76
77You can also set multiple variables with one call.
78
79```javascript
80myModule.__set__({
81 fs: fsMock,
82 path: "/dev/null"
83});
84```
85
86You 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
89myModule.__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
102var revert = myModule.__set__("port", 3000);
103
104// port is now 3000
105revert();
106// port is now the previous value
107```
108
109For your convenience you can also use the `__with__` method which reverts the given changes after it finished.
110
111```javascript
112myModule.__with__({
113 port: 3000
114})(function () {
115 // within this function port is 3000
116});
117// now port is the previous value again
118```
119
120The `__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
123myModule.__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
135Limitations
136-----------
137
138**Babel's ES module emulation**<br>
139During 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>
142Variables 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>
153rewire 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()
157module.exports = 2;
158```
159
160**Globals with invalid variable names**<br>
161rewire imports global variables into the local scope by prepending a list of `var` declarations:
162
163```javascript
164var someGlobalVar = global.someGlobalVar;
165```
166
167If `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>
170Please be aware that you can't rewire `eval()` or the global object itself.
171
172
173<br />
174
175API
176---
177
178### rewire(filename: String): rewiredModule
179
180Returns a rewired version of the module found at `filename`. Use `rewire()` exactly like `require()`.
181
182### rewiredModule.&#95;&#95;set&#95;&#95;(name: String, value: *): Function
183
184Sets the internal variable `name` to the given `value`. Returns a function which can be called to revert the change.
185
186### rewiredModule.&#95;&#95;set&#95;&#95;(obj: Object): Function
187
188Takes 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.&#95;&#95;get&#95;&#95;(name: String): *
191
192Returns the private variable with the given `name`.
193
194### rewiredModule.&#95;&#95;with&#95;&#95;(obj: Object): Function&lt;callback: Function>
195
196Returns 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
200Caveats
201-------
202
203**Difference to require()**<br>
204Every call of rewire() executes the module again and returns a fresh instance.
205
206```javascript
207rewire("./myModule.js") === rewire("./myModule.js"); // = false
208```
209
210This 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>
213Since 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>
216Although 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
219myModule.__set__("console", {
220 log: function () {}
221});
222```
223
224This 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
228webpack
229-------
230See [rewire-webpack](https://github.com/jhnns/rewire-webpack)
231
232<br />
233
234## License
235
236MIT