Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7b21f0f

Browse files
committed
Merge remote-tracking branch 'origin/master'
2 parents 9e54019 + 9dcb9bc commit 7b21f0f

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

README.md

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,43 @@ Installation
2626
Examples
2727
--------
2828

29+
Imagine you want to test this module:
30+
2931
```javascript
30-
var rewire = require("rewire");
32+
// lib/myModule.js
33+
34+
// With rewire you can change all these variables
35+
var fs = require("fs"),
36+
http = require("http"),
37+
someOtherVar = "hi",
38+
myPrivateVar = 1;
39+
40+
function readSomethingFromFileSystem(cb) {
41+
// But no scoped variables
42+
var path = "/somewhere/on/the/disk";
43+
44+
console.log("Reading from file system ...");
45+
fs.readFile(path, "utf8", cb);
46+
}
47+
48+
exports.readSomethingFromFileSystem = readSomethingFromFileSystem;
49+
```
50+
51+
Now within your test module:
3152

53+
```javascript
54+
// test/myModule.test.js
55+
56+
var rewire = require("rewire");
3257

3358
// rewire acts exactly like require.
3459
var myModule = rewire("../lib/myModule.js");
3560

36-
3761
// Just with one difference:
3862
// Your module will now export a special setter and getter for private variables.
3963
myModule.__set__("myPrivateVar", 123);
4064
myModule.__get__("myPrivateVar"); // = 123
4165

42-
4366
// This allows you to mock almost everything within the module e.g. the fs-module.
4467
// Just pass the variable name as first parameter and your mock as second.
4568
myModule.__set__("fs", {
@@ -51,15 +74,13 @@ myModule.readSomethingFromFileSystem(function (err, data) {
5174
console.log(data); // = Success!
5275
});
5376

54-
5577
// You can set different variables with one call.
5678
myModule.__set__({
5779
fs: fsMock,
5880
http: httpMock,
5981
someOtherVar: "hello"
6082
});
6183

62-
6384
// You may also override globals. These changes are only within the module, so
6485
// you don't have to be concerned that other modules are influenced by your mock.
6586
myModule.__set__({
@@ -71,7 +92,6 @@ myModule.__set__({
7192
}
7293
});
7394

74-
7595
// But be careful, if you do something like this you'll change your global
7696
// console instance.
7797
myModule.__set__("console.log", function () { /* be quiet */ });
@@ -145,4 +165,4 @@ var webpackOptions = {
145165
require("rewire").bundlers.webpack(webpackOptions);
146166

147167
webpack("entry.js", webpackOptions, function () {});
148-
```
168+
```

0 commit comments

Comments
 (0)