Welcome to mirror list, hosted at ThFree Co, Russian Federation.

README.md - github.com/twbs/rewire.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8b8884296c59ca91c7c8cbd9bd56a7490ea8be76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
rewire
======
**Easy monkey-patching for node.js unit tests**

[![](https://img.shields.io/npm/v/rewire.svg)](https://www.npmjs.com/package/rewire)
[![](https://img.shields.io/npm/dm/rewire.svg)](https://www.npmjs.com/package/rewire)
[![Dependency Status](https://david-dm.org/jhnns/rewire.svg)](https://david-dm.org/jhnns/rewire)
[![Build Status](https://travis-ci.org/jhnns/rewire.svg?branch=master)](https://travis-ci.org/jhnns/rewire)
[![Coverage Status](https://img.shields.io/coveralls/jhnns/rewire.svg)](https://coveralls.io/r/jhnns/rewire?branch=master)

rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may

- inject mocks for other modules or globals like `process`
- inspect private variables
- override variables within the module.

**Please note:** The current version of rewire is only compatible with CommonJS modules. See [Limitations](https://github.com/jhnns/rewire#limitations).

<br>

Installation
------------

`npm install rewire`

<br />

Introduction
------------

Imagine you want to test this module:

```javascript
// lib/myModule.js
// With rewire you can change all these variables
var fs = require("fs"),
    path = "/somewhere/on/the/disk";

function readSomethingFromFileSystem(cb) {
    console.log("Reading from file system ...");
    fs.readFile(path, "utf8", cb);
}

exports.readSomethingFromFileSystem = readSomethingFromFileSystem;
```

Now within your test module:

```javascript
// test/myModule.test.js
var rewire = require("rewire");

var myModule = rewire("../lib/myModule.js");
```

rewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.

```javascript
myModule.__set__("path", "/dev/null");
myModule.__get__("path"); // = '/dev/null'
```

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.

```javascript
var fsMock = {
    readFile: function (path, encoding, cb) {
        expect(path).to.equal("/somewhere/on/the/disk");
        cb(null, "Success!");
    }
};
myModule.__set__("fs", fsMock);

myModule.readSomethingFromFileSystem(function (err, data) {
    console.log(data); // = Success!
});
```

You can also set multiple variables with one call.

```javascript
myModule.__set__({
    fs: fsMock,
    path: "/dev/null"
});
```

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.

```javascript
myModule.__set__({
    console: {
        log: function () { /* be quiet */ }
    },
    process: {
        argv: ["testArg1", "testArg2"]
    }
});
```

`__set__` returns a function which reverts the changes introduced by this particular `__set__` call

```javascript
var revert = myModule.__set__("port", 3000);

// port is now 3000
revert();
// port is now the previous value
```

For your convenience you can also use the `__with__` method which reverts the given changes after it finished.

```javascript
myModule.__with__({
    port: 3000
})(function () {
    // within this function port is 3000
});
// now port is the previous value again
```

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.

```javascript
myModule.__with__({
    port: 3000
})(function () {
    return new Promise(...);
}).then(function () {
    // now port is the previous value again
});
// port is still 3000 here because the promise hasn't been resolved yet
```

<br />

Limitations
-----------

**Babel's ES module emulation**<br>
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).

**Variables inside functions**<br>
Variables inside functions can not be changed by rewire. This is constrained by the language.

```javascript
// myModule.js
(function () {
    // Can't be changed by rewire
    var someVariable;
})()
```

**Modules that export primitives**<br>
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.

```javascript
// Will throw an error if it's loaded with rewire()
module.exports = 2;
```

**Globals with invalid variable names**<br>
rewire imports global variables into the local scope by prepending a list of `var` declarations:

```javascript
var someGlobalVar = global.someGlobalVar;
```

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**.

**Special globals**<br>
Please be aware that you can't rewire `eval()` or the global object itself.


<br />

API
---

### rewire(filename: String): rewiredModule

Returns a rewired version of the module found at `filename`. Use `rewire()` exactly like `require()`.

### rewiredModule.&#95;&#95;set&#95;&#95;(name: String, value: *): Function

Sets the internal variable `name` to the given `value`. Returns a function which can be called to revert the change.

### rewiredModule.&#95;&#95;set&#95;&#95;(obj: Object): Function

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.

### rewiredModule.&#95;&#95;get&#95;&#95;(name: String): *

Returns the private variable with the given `name`.

### rewiredModule.&#95;&#95;with&#95;&#95;(obj: Object): Function&lt;callback: Function>

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.

<br />

Caveats
-------

**Difference to require()**<br>
Every call of rewire() executes the module again and returns a fresh instance.

```javascript
rewire("./myModule.js") === rewire("./myModule.js"); // = false
```

This can especially be a problem if the module is not idempotent [like mongoose models](https://github.com/jhnns/rewire/issues/27).

**Globals are imported into the module's scope at the time of rewiring**<br>
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).

**Dot notation**<br>
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:

```javascript
myModule.__set__("console", {
    log: function () {}
});
```

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.

<br />

webpack
-------
See [rewire-webpack](https://github.com/jhnns/rewire-webpack)

<br />

CoffeeScript
------------

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.

<br />

## License

MIT