Socket
Socket
Sign inDemoInstall

rewire

Package Overview
Dependencies
0
Maintainers
1
Versions
45
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    rewire

Dependency injection for node.js applications


Version published
Weekly downloads
416K
increased by4.59%
Maintainers
1
Created
Weekly downloads
 

Package description

What is rewire?

Rewire is a testing utility for Node.js that allows you to modify the behavior of a module by overriding its private variables and functions. This is particularly useful for unit testing, as it enables you to test private functions and mock dependencies.

What are rewire's main functionalities?

Accessing Private Variables

This feature allows you to access private variables within a module. In the code sample, `privateVar` is a private variable in `myModule` that is accessed using `__get__`.

const rewire = require('rewire');
const myModule = rewire('./myModule');
const privateVar = myModule.__get__('privateVar');
console.log(privateVar);

Mocking Private Functions

This feature allows you to mock private functions within a module. In the code sample, `privateFunction` is a private function in `myModule` that is mocked using `__set__`.

const rewire = require('rewire');
const myModule = rewire('./myModule');
myModule.__set__('privateFunction', function() { return 'mocked'; });
console.log(myModule.somePublicFunction());

Mocking Dependencies

This feature allows you to mock dependencies of a module. In the code sample, `dependency` is a dependency of `myModule` that is mocked using `__set__`.

const rewire = require('rewire');
const myModule = rewire('./myModule');
myModule.__set__('dependency', { someMethod: () => 'mocked' });
console.log(myModule.somePublicFunction());

Other packages similar to rewire

Changelog

Source

1.1.2

  • Added deprecation warning for client-side bundlers
  • Updated package.json for node v0.10

Readme

Source

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.

If you want to use rewire also on the client-side take a look at client-side bundlers

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

###webpack See rewire-webpack

###browserify rewire currently only supports browserify@1.x. I'm not planing to continue development, but if you're relying on this feature please let me know.


##License

MIT

Keywords

FAQs

Last updated on 13 Mar 2013

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc