Repo of the Day
jhnns/rewire
Published: Oct 31, 2023
Open repository ↗Easy monkey-patching for node.js unit tests
Summary
Rewire is a Node.js testing utility that lets unit tests reach into a CommonJS module and modify its private variables, dependencies, or globals without changing the source code. It behaves like require() but attaches __set__, __get__, and __with__ helpers to the returned module so tests can swap out internals.
What it is useful for
Rewire is useful when you need to test code that depends on things you don't want to actually invoke during a unit test, such as the file system, environment values, or the process object. It also helps when you want to inspect a module's private state or steer execution by changing an internal constant (for example, a path string or a port number). Because overrides are scoped to the rewired module, the rest of your test process is not affected, which the README demonstrates by mocking console and process only inside the target module.
How engineers can use it
Installation is documented as a single command:
npm install rewire
Load a module through rewire instead of require:
var rewire = require("rewire");
var myModule = rewire("../lib/myModule.js");
You can then replace top-level variables. The README shows swapping the fs dependency and a path constant with a mock:
myModule.__set__("path", "/dev/null");
myModule.__set__("fs", {
readFile: function (path, encoding, cb) { cb(null, "Success!"); }
});
__set__ returns a revert function, and __with__ applies changes only for the duration of a callback or a returned promise:
myModule.__with__({ port: 3000 })(function () {
// port is 3000 here
});
// port restored
Several documented limitations matter in practice. Rewire only supports CommonJS modules; Babel's ESM-to-CJS transform renames internal variables and breaks it (the README suggests babel-plugin-rewire as an alternative). It cannot change variables declared inside functions, modules that export a primitive, eval, or the global object. Every call to rewire() re-executes the module, so each test gets a fresh instance, which can cause problems with non-idempotent modules such as Mongoose models. The README also warns that globals are captured when rewire() runs, so installing Sinon's fake timers after rewiring will not affect the rewired copy.