Git Product home page Git Product logo

rewire's Introduction

rewire

Dependency injection for node.js applications.

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 or globals like process
  • 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).

Good news to all caffeine-addicts: rewire works also with Coffee-Script. Note that in this case CS needs to be listed in your devDependencies.

Build Status Dependency Status Dependency tracking by David


Installation

npm install rewire


Examples

Imagine you want to test this module:

// 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:

// 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

##API

###rewire(filename): rewiredModule

  • filename:
    Path to the module that shall be rewired. Use it exactly like require().

###rewiredModule.__set__(name, value)

  • name:
    Name of the variable to set. The variable should be global or defined with var in the top-leve scope of the module.
  • value:
    The value to set.

###rewiredModule.__set__(env)

  • env:
    Takes all keys as variable names and sets the values respectively.

###rewiredModule.__get__(name): value

Returns the private variable.


##Client-Side Bundlers

rewire comes also with support for client-side bundlers. But since it 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:

However, expect this feature to be extracted into own bundler-specific modules soon.

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

rewire currently only supports [email protected]. I'm not planing to continue development, but if you're relying on this feature please let me know.

var b = browserify();

// Add rewire as browserify middleware
b.use(require("rewire").bundlers.browserify);

###webpack

rewire doesn't run with [email protected] because of various breaking api changes. I'm working on that.

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 () {});

##License

MIT

rewire's People

Contributors

jhnns avatar nisaacson avatar suisho avatar tfitos avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.