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: 694c7c4490ebb9ae892388772010747d6c2123f1 (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
rewire
=====
**Dependency injection for node.js applications**.

rewire allows you to modify the behaviour of modules for better unit testing. You may

- provide mocks for other modules
- leak private variables
- override variables within the module
- inject your own scripts

rewire does **not** load the file and eval the contents to emulate node's require mechanism. In fact it uses node's own require to load the module. Thus your module behaves exactly the same in your test environment as under regular circumstances (except your modifications).

**Debugging is fully supported.**

-----------------------------------------------------------------
<br />

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

`npm install rewire`

-----------------------------------------------------------------
<br />

Examples
--------

```javascript
var rewire = require("rewire"),
    rewiredModule;

// Default
////////////////////////////////
// rewire acts exactly like require when omitting all other params
rewire("./myModuleA.js") === require("./myModuleA.js"); // = true



// Mocks
////////////////////////////////
var mockedModuleB = {},
    mockedFs = {},
    mocks = {
        "fs": mockedFs,
        "path/to/moduleB.js": mockedModuleB
    };

// The rewired module will now use your mocks instead of fs
// and moduleB.js. Just make sure that the path is exactly as
// in myModuleA.js required.
rewiredModule = rewire("./myModuleA.js", mocks);



// Injections
////////////////////////////////
var injections = {
        console: {
            log: function () { /* be quiet */ }
        },
        process: { argv: ["someArgs"] },
        __filename: "some/other/dir"
    };

// This will inject
// var console = {log: function () { /* be quiet */ }};
// var process = {argv: ["someArgs"] };
// var __filename = "some/other/dir";
// at the bottom of the module.
// This way you can override private variables within the module
rewiredModule = rewire("./myModuleA.js", null, injections);

// You can also pass a script to inject
rewiredModule =
   rewire("./myModuleA.js", null, "console.log('hellooo');"); // prints "hellooo"



// Leaks
////////////////////////////////
var leaks = ["myPrivateVar1", "myPrivateVar2"];

// This will inject
// module.exports._ = {myPrivateVar1: myPrivateVar1, myPrivateVar2: myPrivateVar2}
// at the bottom of the module.
rewiredModule = rewire("./myModuleA.js", null, null, leaks);

// You now can access your private varialbes under the special __-object
rewiredModule.__.myPrivateVar1; // returns former private variable myPrivateVar1
rewiredModule.__.myPrivateVar2; // returns former private variable myPrivateVar2



// Cache
////////////////////////////////
// By disabling the module cache the rewired module will not be cached.
// Any require()-calls will now return the original module again instead
// of the rewired. Caching is enabled by default.
rewire("./myModuleA.js", null, null, null, false) !==
    require("./myModuleA.js"); // = true

// This removes all rewired modules from require.cache.
rewire.reset();
// IMPORTANT: You should call this before every unit test to ensure
// a clean test environment.
```

-----------------------------------------------------------------
<br />

##API

**rewire(***filename, mocks, injections, leaks, cache***)**

- *{!String} filename*: <br/>
Path to the module that shall be rewired. Use it exactly like require().

- *{Object} mocks (optional)*: <br/>
An object with mocks.

- *{Object|String} injections (optional)*: <br />
If you pass an object, all keys of the object will be `var`s within the module. You can also eval a string.

- *{Array&lt;String&gt;} leaks (optional)*: <br/>
An array with variable names that should be exported. These variables are accessible via `myModule.__`.

- *{Boolean=true} cache (optional)*: <br />
Indicates whether the rewired module should be cached by node so subsequent calls of `require()` will
return the rewired module. Further calls of `rewire()` will always overwrite the cache.

Returns the rewired module.

**rewire.reset()**

Removes all rewired modules from `require.cache`. Every `require()` will now return the original module again.

-----------------------------------------------------------------
<br />

## Please note
### mocks
Keys should be exactly the same like they're required in the target module.
So if you write `require("../../myModules/myModuleA.js")` you need to pass
`{"../../myModules/myModuleA.js": myModuleAMock}`.

### injections
All scripts are injected at the end of the module. So if there is any code in your module
that is executed during `require()`, your injected variables will be undefined at this point.

Imagine `rewire("./myModule.js", null, {console: null});`:

```javascript
console.log("Hello");   // ouch, that won't work. console is undefined at this point because of hoisting

// End of module ///////////////
// rewire will inject here
var console = null;
```

### leaks
Leaks are executed at the end of the module. If a `var` is undefined at this point you
won't be able to access the leak (because `undefined`-values are [copied by value](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language)).
A good approach to this is:

```javascript
var myLeaks = {};

module.exports = function (someValue) {
   myLeaks.someValue = someValue;
};

// End of module ///////////////
// rewire will inject here
module.exports.__ = {myLeaks: myLeaks};
```

Because ```myLeaks``` is defined at the end of the module, you're able to access the leak object and all leaks that
are attached to it later during runtime. Because myLeaks is not exposed under regular circumstances your
module interface stays clean.

### reset
You should call this before every unit test to ensure a clean test environment.

-----------------------------------------------------------------
<br />

## Credits

This module is inspired by the great [injectr](https://github.com/nathanmacinnes/injectr "injectr")-module.

-----------------------------------------------------------------
<br />

## License

(The MIT License)

Copyright (c) 2012 Johannes Ewald &lt;mail@johannesewald.de&gt;

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.