diff options
author | Johannes <mail@johannesewald.de> | 2012-12-12 15:06:30 +0400 |
---|---|---|
committer | Johannes <mail@johannesewald.de> | 2012-12-12 15:06:30 +0400 |
commit | 29e0be66114899702d1c5aff972df042d05634e7 (patch) | |
tree | 86eabee7dbd15320a224c7a02b6ebc112ec824df /README.md | |
parent | db140b9eb9125046ac9e740f8e050b961526db8b (diff) |
Improved examples
Diffstat (limited to 'README.md')
-rw-r--r-- | README.md | 34 |
1 files changed, 27 insertions, 7 deletions
@@ -26,20 +26,43 @@ Installation Examples -------- +Imagine you want to test this module: + ```javascript -var rewire = require("rewire"); +// lib/myModule.js + +// With rewire you can change all these variables +var fs = require("fs"), + http = require("http"), + someOtherVar = "hi", + myPrivateVar = 1; + +function readSomethingFromFileSystem(cb) { + // But no scoped variables + var path; + + 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"); // rewire acts exactly like require. var myModule = rewire("../lib/myModule.js"); - // Just with one difference: // Your module will now export a special setter and getter for private variables. myModule.__set__("myPrivateVar", 123); myModule.__get__("myPrivateVar"); // = 123 - // This allows you to mock almost everything within the module e.g. the fs-module. // Just pass the variable name as first parameter and your mock as second. myModule.__set__("fs", { @@ -51,7 +74,6 @@ myModule.readSomethingFromFileSystem(function (err, data) { console.log(data); // = Success! }); - // You can set different variables with one call. myModule.__set__({ fs: fsMock, @@ -59,7 +81,6 @@ myModule.__set__({ someOtherVar: "hello" }); - // 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. myModule.__set__({ @@ -71,7 +92,6 @@ myModule.__set__({ } }); - // But be careful, if you do something like this you'll change your global // console instance. myModule.__set__("console.log", function () { /* be quiet */ }); @@ -143,4 +163,4 @@ var webpackOptions = { require("rewire").bundlers.webpack(webpackOptions); webpack("entry.js", webpackOptions, function () {}); -```
\ No newline at end of file +``` |