rewire is a monkey-patching tool for Node.js unit tests that modifies module behavior to improve testability.
The tool solves the problem of testing code that depends on external modules or globals by injecting mocks and inspecting private variables. It works by wrapping the require function to add special setter and getter methods to modules. These methods allow tests to override variables in the module's top-level scope, mock dependencies like the fs module, and inspect private state. The __set__ method returns a revert function, and the __with__ method provides a convenience wrapper that automatically reverts changes after a callback completes, with built-in support for promises.
The tool is designed for developers testing CommonJS modules who need to mock dependencies or inspect internal state without refactoring code to expose those internals. It suits projects that rely heavily on unit testing and cannot easily restructure code for testability. The README notes that rewire does not work with Babel's ES module emulation due to variable renaming during transpilation, though other Babel transforms are compatible. The tool cannot modify variables inside functions, attach methods to modules that export primitives, or rewire eval() or the global object itself.
Development activity shows consistent maintenance with regular updates addressing reported issues and edge cases. The project maintains clear documentation of its limitations and provides straightforward API design. Bug fixes and feature requests receive attention, indicating active stewardship of the codebase.