Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

rewire

jhnns1mMIT7.0.0TypeScript support: definitely-typed

Easy dependency injection for node.js unit testing

dependency, injection, mock, shim, module, unit, test, leak, inspect, fake, require

readme

rewire

Easy monkey-patching for node.js unit tests

Coverage Status

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
  • inspect private variables
  • override variables within the module.

Please note: The current version of rewire is only compatible with CommonJS modules. See Limitations.


Installation

npm install rewire


Introduction

Imagine you want to test this module:

// lib/myModule.js
// With rewire you can change all these variables
var fs = require("fs"),
    path = "/somewhere/on/the/disk";

function readSomethingFromFileSystem(cb) {
    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");

var myModule = rewire("../lib/myModule.js");

rewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.

myModule.__set__("path", "/dev/null");
myModule.__get__("path"); // = '/dev/null'

This allows you to mock everything in the top-level scope of the module, like the fs module for example. Just pass the variable name as first parameter and your mock as second.

var fsMock = {
    readFile: function (path, encoding, cb) {
        expect(path).to.equal("/somewhere/on/the/disk");
        cb(null, "Success!");
    }
};
myModule.__set__("fs", fsMock);

myModule.readSomethingFromFileSystem(function (err, data) {
    console.log(data); // = Success!
});

You can also set multiple variables with one call.

myModule.__set__({
    fs: fsMock,
    path: "/dev/null"
});

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"]
    }
});

__set__ returns a function which reverts the changes introduced by this particular __set__ call

var revert = myModule.__set__("port", 3000);

// port is now 3000
revert();
// port is now the previous value

For your convenience you can also use the __with__ method which reverts the given changes after it finished.

myModule.__with__({
    port: 3000
})(function () {
    // within this function port is 3000
});
// now port is the previous value again

The __with__ method is also aware of promises. If a thenable is returned all changes stay until the promise has either been resolved or rejected.

myModule.__with__({
    port: 3000
})(function () {
    return new Promise(...);
}).then(function () {
    // now port is the previous value again
});
// port is still 3000 here because the promise hasn't been resolved yet

Limitations

Babel's ES module emulation
During the transpilation step from ESM to CJS modules, Babel renames internal variables. Rewire will not work in these cases (see #62). Other Babel transforms, however, should be fine. Another solution might be switching to babel-plugin-rewire.

Variables inside functions
Variables inside functions can not be changed by rewire. This is constrained by the language.

// myModule.js
(function () {
    // Can't be changed by rewire
    var someVariable;
})()

Modules that export primitives
rewire is not able to attach the __set__- and __get__-method if your module is just exporting a primitive. Rewiring does not work in this case.

// Will throw an error if it's loaded with rewire()
module.exports = 2;

Globals with invalid variable names
rewire imports global variables into the local scope by prepending a list of var declarations:

var someGlobalVar = global.someGlobalVar;

If someGlobalVar is not a valid variable name, rewire just ignores it. In this case you're not able to override the global variable locally.

Special globals
Please be aware that you can't rewire eval() or the global object itself.


API

rewire(filename: String): rewiredModule

Returns a rewired version of the module found at filename. Use rewire() exactly like require().

rewiredModule.__set__(name: String, value: *): Function

Sets the internal variable name to the given value. Returns a function which can be called to revert the change.

rewiredModule.__set__(obj: Object): Function

Takes all enumerable keys of obj as variable names and sets the values respectively. Returns a function which can be called to revert the change.

rewiredModule.__get__(name: String): *

Returns the private variable with the given name.

rewiredModule.__with__(obj: Object): Function<callback: Function>

Returns a function which - when being called - sets obj, executes the given callback and reverts obj. If callback returns a promise, obj is only reverted after the promise has been resolved or rejected. For your convenience the returned function passes the received promise through.


Caveats

Difference to require()
Every call of rewire() executes the module again and returns a fresh instance.

rewire("./myModule.js") === rewire("./myModule.js"); // = false

This can especially be a problem if the module is not idempotent like mongoose models.

Globals are imported into the module's scope at the time of rewiring
Since rewire imports all gobals into the module's scope at the time of rewiring, property changes on the global object after that are not recognized anymore. This is a problem when using sinon's fake timers after you've called rewire().

Dot notation
Although it is possible to use dot notation when calling __set__, it is strongly discouraged in most cases. For instance, writing myModule.__set__("console.log", fn) is effectively the same as just writing console.log = fn. It would be better to write:

myModule.__set__("console", {
    log: function () {}
});

This replaces console just inside myModule. That is, because rewire is using eval() to turn the key expression into an assignment. Hence, calling myModule.__set__("console.log", fn) modifies the log function on the global console object.


webpack

See rewire-webpack


License

MIT

changelog

Changelog

7.0.0

6.0.0

  • Breaking: Remove Node v8 support. We had to do this because one of our dependencies had security issues and the version with the fix dropped Node v8 as well.
  • Update dependencies #193
  • Fix Modifying globals within module leaks to global with Node >=10 #167
  • Fixed import errors on modules with shebang declarations #179

5.0.0

  • Breaking: Remove Node v6 support. We had to do this because one of our dependencies had security issues and the version with the fix dropped Node v6 as well.
  • Update dependencies #159 #172 #154 #166

4.0.1

  • Fix a bug where const was not properly detected #139

4.0.0

  • Breaking: Remove official node v4 support. It probably still works with node v4, but no guarantees anymore.
  • Potentially breaking: Replace babel with regex-based transformation 9b77ed9a293c538ec3eb5160bcb933e012ce517f. This should not break, but it has been flagged as major version bump as the regex might not catch all cases reliably and thus fail for some users.
  • Improve runtime performance #132
  • Use coffeescript package in favor of deprecated coffee-script #134

3.0.2

  • Fix a bug where rewire used the project's .babelrc #119 #123

3.0.1

  • Fix Unknown Plugin "transform-es2015-block-scoping" #121 #122

3.0.0

  • Breaking: Remove support for node versions below 4
  • Add support for const #79 #95 #117 #118

2.5.2

  • Fix cluttering of require.extensions even if CoffeeScript is not installed #98

2.5.1

  • Ignore modules that export non-extensible values like primitives or sealed objects #83

2.5.0

  • Provide shared test cases to other modules that mimic rewire's behavior in other environments jhnns/rewire-webpack#18

2.4.0

  • Make rewire's special methods __set__, __get__ and __with__ writable #78

2.3.4

  • Add license and keywords to package.json #59 #60

2.3.3

  • Fix issue where the strict mode was not detected when a comment was before "strict mode"; #54

2.3.2

  • Fix a problem when a function declaration had the same name as a global variable #56
  • Add README section about rewire's limitations

2.3.1

  • Fix problems when global objects like JSON, etc. have been rewired #40

2.3.0

  • Add possibility to mock undefined, implicit globals #35

2.2.0

  • Add support for dot notation in set(env) calls #39

2.1.5

  • Fix issues with reverting nested properties #39

2.1.4

  • Fix problems when an illegal variable name is used for a global

2.1.3

  • Fix shadowing of internal module, exports and require when a global counterpart exists jhnns/rewire-webpack#6

2.1.2

  • Fixed missing var statement which lead to pollution of global namespace #33

2.1.1

  • Made magic __set__, __get__ and __with__ not enumerable #32

2.1.0

  • Added revert feature of __set__ method
  • Introduced __with__ method to revert changes automatically

2.0.1

  • Added test coverage tool
  • Small README and description changes

2.0.0

1.1.3

  • Removed IDE stuff from npm package

1.1.2

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

1.1.1

  • Fixed bug with modules that had a comment on the last line

1.1.0

  • Added Coffee-Script support
  • Removed Makefile: Use npm test instead.

1.0.4

  • Improved client-side rewire() with webpack

1.0.3

  • Fixed error with client-side bundlers when a module was ending with a comment

1.0.2

  • Improved strict mode detection

1.0.1

  • Fixed crash when a global module has been used in the browser

1.0.0

  • Removed caching functionality. Now rewire doesn't modify require.cache at all
  • Added support for webpack-bundler
  • Moved browserify-middleware from rewire.browserify to rewire.bundlers.browserify
  • Reached stable state :)