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 | [![Dependency Status](https://david-dm.org/jhnns/rewire.svg)](https://david-dm.org/jhnns/rewire)
|
8 | [![Build Status](https://travis-ci.org/jhnns/rewire.svg?branch=master)](https://travis-ci.org/jhnns/rewire)
|
9 | [![Coverage Status](https://img.shields.io/coveralls/jhnns/rewire.svg)](https://coveralls.io/r/jhnns/rewire?branch=master)
|
10 |
|
11 | rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may
|
12 |
|
13 | - inject mocks for other modules or globals like `process`
|
14 | - inspect private variables
|
15 | - override variables within the module.
|
16 |
|
17 | **Please note:** The current version of rewire is only compatible with CommonJS modules. See [Limitations](https://github.com/jhnns/rewire#limitations).
|
18 |
|
19 | <br>
|
20 |
|
21 | Installation
|
22 | ------------
|
23 |
|
24 | `npm install rewire`
|
25 |
|
26 | <br />
|
27 |
|
28 | Introduction
|
29 | ------------
|
30 |
|
31 | Imagine you want to test this module:
|
32 |
|
33 | ```javascript
|
34 | // lib/myModule.js
|
35 | // With rewire you can change all these variables
|
36 | var fs = require("fs"),
|
37 | path = "/somewhere/on/the/disk";
|
38 |
|
39 | function readSomethingFromFileSystem(cb) {
|
40 | console.log("Reading from file system ...");
|
41 | fs.readFile(path, "utf8", cb);
|
42 | }
|
43 |
|
44 | exports.readSomethingFromFileSystem = readSomethingFromFileSystem;
|
45 | ```
|
46 |
|
47 | Now within your test module:
|
48 |
|
49 | ```javascript
|
50 | // test/myModule.test.js
|
51 | var rewire = require("rewire");
|
52 |
|
53 | var myModule = rewire("../lib/myModule.js");
|
54 | ```
|
55 |
|
56 | rewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.
|
57 |
|
58 | ```javascript
|
59 | myModule.__set__("path", "/dev/null");
|
60 | myModule.__get__("path"); // = '/dev/null'
|
61 | ```
|
62 |
|
63 | 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.
|
64 |
|
65 | ```javascript
|
66 | var fsMock = {
|
67 | readFile: function (path, encoding, cb) {
|
68 | expect(path).to.equal("/somewhere/on/the/disk");
|
69 | cb(null, "Success!");
|
70 | }
|
71 | };
|
72 | myModule.__set__("fs", fsMock);
|
73 |
|
74 | myModule.readSomethingFromFileSystem(function (err, data) {
|
75 | console.log(data); // = Success!
|
76 | });
|
77 | ```
|
78 |
|
79 | You can also set multiple variables with one call.
|
80 |
|
81 | ```javascript
|
82 | myModule.__set__({
|
83 | fs: fsMock,
|
84 | path: "/dev/null"
|
85 | });
|
86 | ```
|
87 |
|
88 | 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.
|
89 |
|
90 | ```javascript
|
91 | myModule.__set__({
|
92 | console: {
|
93 | log: function () { /* be quiet */ }
|
94 | },
|
95 | process: {
|
96 | argv: ["testArg1", "testArg2"]
|
97 | }
|
98 | });
|
99 | ```
|
100 |
|
101 | `__set__` returns a function which reverts the changes introduced by this particular `__set__` call
|
102 |
|
103 | ```javascript
|
104 | var revert = myModule.__set__("port", 3000);
|
105 |
|
106 | // port is now 3000
|
107 | revert();
|
108 | // port is now the previous value
|
109 | ```
|
110 |
|
111 | For your convenience you can also use the `__with__` method which reverts the given changes after it finished.
|
112 |
|
113 | ```javascript
|
114 | myModule.__with__({
|
115 | port: 3000
|
116 | })(function () {
|
117 | // within this function port is 3000
|
118 | });
|
119 | // now port is the previous value again
|
120 | ```
|
121 |
|
122 | 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.
|
123 |
|
124 | ```javascript
|
125 | myModule.__with__({
|
126 | port: 3000
|
127 | })(function () {
|
128 | return new Promise(...);
|
129 | }).then(function () {
|
130 | // now port is the previous value again
|
131 | });
|
132 | // port is still 3000 here because the promise hasn't been resolved yet
|
133 | ```
|
134 |
|
135 | <br />
|
136 |
|
137 | Limitations
|
138 | -----------
|
139 |
|
140 | **Babel's ES module emulation**<br>
|
141 | 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).
|
142 |
|
143 | **Variables inside functions**<br>
|
144 | Variables inside functions can not be changed by rewire. This is constrained by the language.
|
145 |
|
146 | ```javascript
|
147 | // myModule.js
|
148 | (function () {
|
149 | // Can't be changed by rewire
|
150 | var someVariable;
|
151 | })()
|
152 | ```
|
153 |
|
154 | **Modules that export primitives**<br>
|
155 | 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.
|
156 |
|
157 | ```javascript
|
158 | // Will throw an error if it's loaded with rewire()
|
159 | module.exports = 2;
|
160 | ```
|
161 |
|
162 | **Globals with invalid variable names**<br>
|
163 | rewire imports global variables into the local scope by prepending a list of `var` declarations:
|
164 |
|
165 | ```javascript
|
166 | var someGlobalVar = global.someGlobalVar;
|
167 | ```
|
168 |
|
169 | 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**.
|
170 |
|
171 | **Special globals**<br>
|
172 | Please be aware that you can't rewire `eval()` or the global object itself.
|
173 |
|
174 |
|
175 | <br />
|
176 |
|
177 | API
|
178 | ---
|
179 |
|
180 | ### rewire(filename: String): rewiredModule
|
181 |
|
182 | Returns a rewired version of the module found at `filename`. Use `rewire()` exactly like `require()`.
|
183 |
|
184 | ### rewiredModule.__set__(name: String, value: *): Function
|
185 |
|
186 | Sets the internal variable `name` to the given `value`. Returns a function which can be called to revert the change.
|
187 |
|
188 | ### rewiredModule.__set__(obj: Object): Function
|
189 |
|
190 | 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.
|
191 |
|
192 | ### rewiredModule.__get__(name: String): *
|
193 |
|
194 | Returns the private variable with the given `name`.
|
195 |
|
196 | ### rewiredModule.__with__(obj: Object): Function<callback: Function>
|
197 |
|
198 | 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.
|
199 |
|
200 | <br />
|
201 |
|
202 | Caveats
|
203 | -------
|
204 |
|
205 | **Difference to require()**<br>
|
206 | Every call of rewire() executes the module again and returns a fresh instance.
|
207 |
|
208 | ```javascript
|
209 | rewire("./myModule.js") === rewire("./myModule.js"); // = false
|
210 | ```
|
211 |
|
212 | This can especially be a problem if the module is not idempotent [like mongoose models](https://github.com/jhnns/rewire/issues/27).
|
213 |
|
214 | **Globals are imported into the module's scope at the time of rewiring**<br>
|
215 | 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).
|
216 |
|
217 | **Dot notation**<br>
|
218 | 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:
|
219 |
|
220 | ```javascript
|
221 | myModule.__set__("console", {
|
222 | log: function () {}
|
223 | });
|
224 | ```
|
225 |
|
226 | 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.
|
227 |
|
228 | <br />
|
229 |
|
230 | webpack
|
231 | -------
|
232 | See [rewire-webpack](https://github.com/jhnns/rewire-webpack)
|
233 |
|
234 | <br />
|
235 |
|
236 | CoffeeScript
|
237 | ------------
|
238 |
|
239 | Good news to all caffeine-addicts: rewire works also with [Coffee-Script](http://coffeescript.org/). Note that in this case you need to install the `coffeescript` package.
|
240 |
|
241 | <br />
|
242 |
|
243 | ## License
|
244 |
|
245 | MIT
|