Skip to content

Commit

Permalink
- transferred files from rewire
Browse files Browse the repository at this point in the history
- updated package.json
  • Loading branch information
jhnns committed Feb 23, 2013
1 parent a10bfd7 commit a3179ef
Show file tree
Hide file tree
Showing 14 changed files with 440 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Expand Up @@ -11,4 +11,5 @@ pids
logs
results

npm-debug.log
node_modules
npm-debug.log
6 changes: 6 additions & 0 deletions .travis.yml
@@ -0,0 +1,6 @@
language: node_js
node_js:
- 0.8

script:
- npm test
2 changes: 2 additions & 0 deletions CHANGELOG.md
@@ -0,0 +1,2 @@
##Changelog

19 changes: 19 additions & 0 deletions LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2013 Johannes Ewald
MIT LICENSE

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.
172 changes: 169 additions & 3 deletions README.md
@@ -1,4 +1,170 @@
rewire-webpack
==============
rewire
=====
**Dependency injection for node.js applications**.

Dependency injection for webpack bundles
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
- leak private variables
- override variables within the module.

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

Furthermore rewire comes also with support for various client-side bundlers (see [below](#client-side-bundlers)).

[![Build Status](https://secure.travis-ci.org/jhnns/rewire.png?branch=master)](http://travis-ci.org/jhnns/rewire)
[![Dependency Status](http://david-dm.org/jhnns/rewire/status.png)](http://david-dm.org/jhnns/rewire)
Dependency tracking by [David](http://david-dm.org/)

<br />

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

`npm install rewire`

<br />

Examples
--------

Imagine you want to test this module:

```javascript
// 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 = "/somewhere/on/the/disk";

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", {
readFile: function (path, encoding, cb) {
cb(null, "Success!");
}
});
myModule.readSomethingFromFileSystem(function (err, data) {
console.log(data); // = Success!
});

// You can set different variables with one call.
myModule.__set__({
fs: fsMock,
http: httpMock,
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__({
console: {
log: function () { /* be quiet */ }
},
process: {
argv: ["testArg1", "testArg2"]
}
});

// But be careful, if you do something like this you'll change your global
// console instance.
myModule.__set__("console.log", function () { /* be quiet */ });

// There is another difference to require:
// Every call of rewire() returns a new instance.
rewire("./myModule.js") === rewire("./myModule.js"); // = false
```

<br />

##API

###rewire(filename): rewiredModule

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

###rewiredModule.&#95;&#95;set&#95;&#95;(name, value)

- *name*: <br/>
Name of the variable to set. The variable should be global or defined with `var` in the top-leve scope of the module.
- *value*: <br/>
The value to set.

###rewiredModule.&#95;&#95;set&#95;&#95;(env)
- *env*: <br/>
Takes all keys as variable names and sets the values respectively.

###rewiredModule.&#95;&#95;get&#95;&#95;(name): value

Returns the private variable.

<br />

##Client-Side Bundlers
Since rewire relies heavily on node's require mechanism it can't be used on the client-side without adding special middleware to the bundling process. Currently supported bundlers are:

- [browserify](https://github.com/substack/node-browserify)
- [webpack](https://github.com/webpack/webpack) < 0.9.x

**Please note:** Unfortunately the line numbers in stack traces have an offset of +2 (browserify) / +1 (webpack).
This is caused by generated code that is added during the bundling process.

###browserify

```javascript
var b = browserify(),
bundleSrc;

// Add rewire as browserify middleware
// @see https://github.com/substack/node-browserify/blob/master/doc/methods.markdown#busefn
b.use(require("rewire").bundlers.browserify);

b.addEntry("entry.js");
bundleSrc = b.bundle();
```

###webpack

rewire doesn't run with webpack 0.9 because of various breaking api changes. I'm working on that.

```javascript
var webpackOptions = {
output: "bundle.js"
};

// This function modifies the webpack options object.
// It adds a postLoader and postProcessor to the bundling process.
// @see https://github.com/webpack/webpack#programmatically-usage
require("rewire").bundlers.webpack(webpackOptions);

webpack("entry.js", webpackOptions, function () {});
```
25 changes: 25 additions & 0 deletions lib/RewireLoader.js
@@ -0,0 +1,25 @@
var __get__ = require("rewire/lib/__get__.js"),
__set__ = require("rewire/lib/__set__.js"),
getImportGlobalsSrc = require("rewire/lib/getImportGlobalsSrc.js"),
detectStrictMode = require("rewire/lib/detectStrictMode.js");

module.exports = function(src) {
// append at least a newline, the source may end with a line comment
var prepend, append = "\n";

// We prepend a list of all globals declared with var so they can be overridden (without changing original globals)
prepend = getImportGlobalsSrc();

// We append our special setter and getter.
append += "module.exports.__set__ = " + __set__.toString() + "; ";
append += "module.exports.__get__ = " + __get__.toString() + "; ";

// Check if the module uses the strict mode.
// If so we must ensure that "use strict"; stays at the beginning of the module.
if (detectStrictMode(src) === true) {
prepend = ' "use strict"; ' + prepend;
}

// Let the show begin
return prepend + src + append;
};
37 changes: 37 additions & 0 deletions lib/RewirePlugin.js
@@ -0,0 +1,37 @@
var path = require("path");
var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin");
var RewiredNormalModuleFactory = require("./RewiredNormalModuleFactory");
var RewiredDependency = require("./RewiredDependency");

function RewirePlugin() {}
module.exports = RewirePlugin;

RewirePlugin.prototype.apply = function(compiler) {
// wire our RewiredDependency to our RewiredNormalModuleFactory
// by decorating the original factory
compiler.plugin("compilation", function(compilation, params) {
var normalModuleFactory = params.normalModuleFactory;
var rewiredNormalModuleFactory = new RewiredNormalModuleFactory(normalModuleFactory);

compilation.dependencyFactories.set(RewiredDependency, rewiredNormalModuleFactory);
compilation.dependencyTemplates.set(RewiredDependency, new RewiredDependency.Template());
});
// accept "var rewire", elsewise it would not be parsed (as overwritten)
compiler.parser.plugin("var rewire", function(expr) {
return true;
});
// find rewire(request: String) calls and bind our RewiredDependency
compiler.parser.plugin("call rewire", function(expr) {
if(expr.arguments.length !== 1) return;
var param = this.evaluateExpression(expr.arguments[0]);
if(!param.isString()) return;
var dep = new RewiredDependency(param.string, param.range);
dep.loc = expr.loc;
this.state.current.addDependency(dep);
return true;
});
// alias the require("rewire") to a webpack rewire
compiler.resolvers.normal.apply(new ModuleAliasPlugin({
rewire: path.join(__dirname, "rewire.js")
}));
};
13 changes: 13 additions & 0 deletions lib/RewiredDependency.js
@@ -0,0 +1,13 @@
var ModuleDependency = require("webpack/lib/dependencies/ModuleDependency");

function RewiredDependency(request, range) {
ModuleDependency.call(this, request);
this.Class = RewiredDependency;
this.range = range;
}
module.exports = RewiredDependency;

RewiredDependency.prototype = Object.create(ModuleDependency.prototype);
RewiredDependency.prototype.type = "rewire";

RewiredDependency.Template = require("webpack/lib/dependencies/ModuleDependencyTemplateAsId");
17 changes: 17 additions & 0 deletions lib/RewiredNormalModuleFactory.js
@@ -0,0 +1,17 @@
var path = require("path");

function RewiredNormalModuleFactory(factory) {
this.factory = factory;
}

module.exports = RewiredNormalModuleFactory;

RewiredNormalModuleFactory.prototype.create = function(context, dependency, callback) {
this.factory.create(context, dependency, function(err, module) {
if(err) return callback(err);
module.request += " rewired";
module.userRequest += "(rewired)";
module.loaders.unshift(path.join(__dirname, "RewireLoader.js"));
return callback(null, module);
});
};
12 changes: 12 additions & 0 deletions lib/rewire.js
@@ -0,0 +1,12 @@
/* rewire module loader */

module.exports = function rewire(module) {
var rewiredModule = {
id: module,
loaded: false,
exports: {}
};
__webpack_modules__[module].call(null, rewiredModule, rewiredModule.exports, __webpack_require__);
rewiredModule.loaded = true;
return rewiredModule.exports;
};
40 changes: 40 additions & 0 deletions package.json
@@ -0,0 +1,40 @@
{
"name" : "rewire-webpack",
"version" : "0.0.0",
"description" : "Dependency injection for webpack bundles",
"keywords" : [
"dependency",
"injection",
"mock",
"unit",
"test",
"leak",
"inspect"
],
"author" : {
"name" : "Johannes Ewald",
"email" : "mail@johannesewald.de"
},
"main" : "lib/index.js",
"homepage": "https://github.com/jhnns/rewire-webpack",
"repository": "git://github.com/jhnns/rewire-webpack.git",
"engines" : {
"node" : "<0.9.x"
},
"dependencies": {
"enhanced-resolve": "0.5.x",
"rewire": "1.x"
},
"devDependencies": {
"mocha": "1.x",
"expect.js": "0.x",
"webpack": "0.9.x",
"css-loader": "0.5.x",
"style-loader": "0.5.x",
"mocha-loader": "0.5.x",
"chai": "1.5.x"
},
"scripts" : {
"test" : "node node_modules/mocha/bin/mocha -R spec"
}
}
17 changes: 17 additions & 0 deletions test/README.md
@@ -0,0 +1,17 @@
# rewire webpack tests

Install the webpack dev server globally:

``` text
npm install webpack-dev-server -g
```

Then run the tests with:

``` text
webpack-dev-server --colors --devtool eval
```

The arguments are optional.

Then open [http://localhost:8080/](http://localhost:8080/)...

0 comments on commit a3179ef

Please sign in to comment.