Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf36825a

Browse files
committed
added documentation
1 parentb4b2794 commitf36825a

File tree

6 files changed

+134
-16
lines changed

6 files changed

+134
-16
lines changed

‎README.md

Lines changed: 80 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,21 @@ rewire allows you to modify the behaviour of modules for better unit testing. Yo
77
- provide mocks for other modules
88
- leak private variables
99
- override variables within the module
10-
- inject scripts
10+
- injectyour ownscripts
1111

12-
rewire does**not** load the file and eval it to emulate node's require mechanism. In fact it uses node's require to load the module. Thus your module behaves exactly the same in your test environment as under regular circumstances (except your modifications).
12+
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).
13+
14+
**Debugging is fully supported.**
15+
16+
-----------------------------------------------------------------
1317

1418
Installation
1519
------------
1620

1721
```npm install rewire```
1822

23+
-----------------------------------------------------------------
24+
1925
Examples
2026
--------
2127

@@ -28,17 +34,20 @@ var rewire = require("rewire"),
2834
// rewire acts exactly like require when omitting all other params
2935
rewiredModule=rewire("./myModuleA.js");
3036

37+
38+
3139
// Mocks
3240
////////////////////////////////
3341
var mockedModuleB= {},
3442
mocks= {
3543
"path/to/moduleB.js": mockedModuleB
3644
};
3745

38-
//the rewired module will now use your mock instead of moduleB.js.
46+
//The rewired module will now use your mock instead of moduleB.js.
3947
rewiredModule=rewire("./myModuleA.js", mocks);
4048

4149

50+
4251
// Injections
4352
////////////////////////////////
4453
var injections= {
@@ -49,13 +58,79 @@ var injections = {
4958
__filename:"some/other/dir"
5059
};
5160

52-
// overrides all given variables within the module
61+
// This will inject
62+
// var console = {log: function () { /* be quiet */ }};
63+
// var process = {argv: ["someArgs"] };
64+
// var __filename = "some/other/dir";
65+
// at the bottom of the module.
66+
// This way you can override private variables within the module
5367
rewiredModule=rewire("./myModuleA.js",null, injections);
54-
// you can also pass a script to inject
68+
69+
// You can also pass a script to inject
5570
rewiredModule=rewire("./myModuleA.js",null,"console.log('hellooo');");
5671

5772

73+
5874
// Leaks
5975
////////////////////////////////
76+
var leaks= ["myPrivateVar1","myPrivateVar2"];
77+
78+
// rewire exports variables under the special "__"-object.
79+
rewiredModule=rewire("./myModuleA.js",null,null, leaks);
80+
console.log(rewiredModule.__.myPrivateVar1);
81+
console.log(rewiredModule.__.myPrivateVar2);
82+
6083

84+
85+
// Cache
86+
////////////////////////////////
87+
// By disabling the module cache the rewired module will not be cached.
88+
// Any later require()-calls within other modules will now return the original
89+
// module again instead of the rewired. Caching is enabled by default.
90+
rewiredModule=rewire("./myModuleA.js",null,null,null,false);
6191
```
92+
93+
-----------------------------------------------------------------
94+
95+
##API
96+
97+
**rewire(***filename, mocks\*, injections\*, leaks\*, cache=true*)\* = optional
98+
99+
-*{!String}**filename***: Path to the module that shall be rewired. Use it exactly like require().
100+
-*{Object}**mocks***: An object with mocks. Keys should be the exactly 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}```.
101+
-*{Object|String}**injections***: If you pass an object, all keys of the object will be```var```s within the module. You can also eval a string.**Please note**: 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. For example: passing```{console: {...}}``` will cause all calls of```console.log()``` to throw an exception if they're executed during```require()```.
102+
-*{Array<String>}**leaks***: An array with variable names that should be exported. These variables are accessible via```myModule.__```
103+
-*{Boolean=true}**cache***: Indicates whether the rewired module should be cached by node so subsequent calls of```require()``` will return the rewired module. Subsequent calls of```rewire()``` will always overwrite the cache.
104+
105+
-----------------------------------------------------------------
106+
107+
##Credits
108+
109+
This module is inspired by the great[injectr](https://github.com/nathanmacinnes/injectr"injectr")-module.
110+
111+
-----------------------------------------------------------------
112+
113+
##License
114+
115+
(The MIT License)
116+
117+
Copyright (c) 2012 Johannes Ewald<mail@johannesewald.de>
118+
119+
Permission is hereby granted, free of charge, to any person obtaining
120+
a copy of this software and associated documentation files (the
121+
'Software'), to deal in the Software without restriction, including
122+
without limitation the rights to use, copy, modify, merge, publish,
123+
distribute, sublicense, and/or sell copies of the Software, and to
124+
permit persons to whom the Software is furnished to do so, subject to
125+
the following conditions:
126+
127+
The above copyright notice and this permission notice shall be
128+
included in all copies or substantial portions of the Software.
129+
130+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
131+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
132+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
133+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
134+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
135+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
136+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

‎lib/getInjectionSrc.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,16 @@
22

33
vartoSrc=require("toSrc");
44

5-
functiongetMonkeyPatchSrc(obj){
5+
/**
6+
* Returns the source code for injecting vars.
7+
*
8+
* e.g.:
9+
* "var console=123;"
10+
*
11+
*@param {Object} obj
12+
*@return {String}
13+
*/
14+
functiongetInjectionSrc(obj){
615
functionwalkObj(obj,level){
716
varkey,
817
value,
@@ -12,7 +21,7 @@ function getMonkeyPatchSrc(obj) {
1221
if(obj.hasOwnProperty(key)){
1322
value=obj[key];
1423
if(level===0){
15-
src+="var ";// on the top level, we need a var statement to override variables
24+
src+="var ";// on the top level we need a var statement
1625
}
1726
src+=key+"="+toSrc(value,9999)+";";
1827
}
@@ -25,4 +34,4 @@ function getMonkeyPatchSrc(obj) {
2534
returnwalkObj(obj,0);
2635
}
2736

28-
module.exports=getMonkeyPatchSrc;
37+
module.exports=getInjectionSrc;

‎lib/getLeakingSrc.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
"use strict";// run code in ES5 strict mode
22

3+
/**
4+
* Returns the source code that will leak private vars.
5+
*
6+
* e.g.:
7+
* "exports.__ = {myPrivateVar: myPrivateVar};"
8+
*
9+
*@param {Array<String>} leaks
10+
*@return {String}
11+
*/
312
functiongetLeakingSrc(leaks){
413
varsrc="exports.__ = {",
514
varName,

‎lib/index.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,26 @@
11
"use strict";// run code in ES5 strict mode
22

3-
varrewire=require("./rewire.js");
3+
varrewireModule=require("./rewire.js");
44

5-
module.exports=function(request,mocks,injections,leaks,cache){
5+
/**
6+
* This function is needed to determine the calling parent module.
7+
* Thus rewire acts exactly the same like require() in the test module.
8+
*
9+
*@param {!String} request Path to the module that shall be rewired. Use it exactly like require().
10+
*@param {Object} mocks An object with mocks. Keys should be the exactly 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}.
11+
*@param {Object} injections If you pass an object, all keys of the object will be vars within the module. You can also eval a string. Please note: 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. For example: passing {console: {...}} will cause all calls of console.log() to throw an exception if they're executed during require().
12+
*@param {Array} leaks An array with variable names that should be exported. These variables are accessible via myModule.__
13+
*@param {Boolean} cache Indicates whether the rewired module should be cached by node so subsequent calls of require() will return the rewired module. Subsequent calls of rewire() will always overwrite the cache.
14+
*@return {*} the rewired module
15+
*/
16+
functionrewire(request,mocks,injections,leaks,cache){
617
deleterequire.cache[__filename];// deleting self from module cache so the parent module is always up to date
718

819
if(cache===undefined){
920
cache=true;
1021
}
1122

12-
returnrewire(module.parent,request,mocks,injections,leaks,cache);
13-
};
23+
returnrewireModule(module.parent,request,mocks,injections,leaks,cache);
24+
}
25+
26+
module.exports=rewire;

‎lib/rewire.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ function restoreOriginalWrappers() {
1010
Module.wrapper[1]=nodeWrapper1;
1111
}
1212

13-
functionrewire(parentModule,filename,mocks,injections,leaks,cache){
13+
/**
14+
* Does actual rewiring the module. For further documentation @see index.js
15+
*/
16+
module.exports=functiondoRewire(parentModule,filename,mocks,injections,leaks,cache){
1417
vartestModule,
1518
nodeRequire,
1619
wrapperExtensions="";
@@ -60,6 +63,4 @@ function rewire(parentModule, filename, mocks, injections, leaks, cache) {
6063
restoreOriginalWrappers();// this is only necessary if nothing has been required within the module
6164

6265
returntestModule.exports;
63-
}
64-
65-
module.exports=rewire;
66+
};

‎test/rewire.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,4 +109,15 @@ describe("#rewire", function () {
109109
rewired.requireIndex();
110110
expect(rewired.index.b).not.to.be(rewired);
111111
});
112+
it("should not influence the original node require if nothing has been required within the rewired module",function(){
113+
varmoduleCMock={},
114+
moduleB,
115+
mocks={
116+
"../C/moduleC.js":moduleCMock
117+
};
118+
119+
rewire("./testModules/C/moduleC.js",mocks);// nothing happens here because moduleC doesn't require anything
120+
moduleB=require("./testModules/A/moduleA.js");// if restoring the original node require didn't worked, the mock would be applied now
121+
expect(moduleB.c).not.to.be(moduleCMock);
122+
});
112123
});

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp