DEV.co
Open-Source Testing · jhnns

rewire

Rewire is a Node.js testing utility that enables monkey-patching of module internals for unit tests. It allows developers to inject mocks, inspect private variables, and override module behavior without modifying source code—useful for isolating dependencies during testing.

Source: GitHub — github.com/jhnns/rewire
3.1k
GitHub stars
128
Forks
JavaScript
Primary language
MIT
License (OSI-approved)

Key facts

Objective fields from the source. Values we can't verify are shown as “Unknown” rather than guessed.

FieldValue
Repositoryjhnns/rewire
Ownerjhnns
Primary languageJavaScript
LicenseMIT — OSI-approved
Stars3.1k
Forks128
Open issues51
Latest releasev9.0.1 (2025-08-15)
Last updated2025-12-11
Sourcehttps://github.com/jhnns/rewire

What rewire is

Rewire instruments CommonJS modules to expose `__set__`, `__get__`, and `__with__` methods, enabling runtime mutation of module-scoped variables and globals within test isolation boundaries. It re-executes modules on each rewire() call and uses eval-based assignment to achieve variable override semantics.

Quickstart

Get the rewire source

Clone the repository and explore it locally.

terminalbash
git clone https://github.com/jhnns/rewire.gitcd rewire# follow the project's README for install & configuration

Need it deployed, integrated, or customized instead? DEV.co ships production installs.

Best use cases

Isolating file I/O and external APIs in unit tests

Replace fs, http, and other modules with mocks without modifying the module under test. Verify call expectations and return controlled responses.

Testing private functions and module-level state

Use __get__ to inspect or assert on private variables, and __set__ to manipulate state before testing public exports without needing complex factories or refactoring.

Mocking process and global object behavior

Override process.argv, console methods, timers, or other globals scoped to a single module under test, isolating test side effects from other tests.

Implementation considerations

  • Each rewire() call returns a fresh module instance; identity checks (===) across calls will fail—cache rewired modules if needed.
  • Variables declared inside functions cannot be rewired; only module-level scope and globals are patchable—structure code accordingly.
  • Using dot notation (e.g., __set__('console.log', fn)) mutates the global object, not the module-local binding; pass objects instead (e.g., __set__('console', {...})).
  • Promise-aware __with__() will delay reversion until resolution; use for async tests but be aware of cleanup timing in test runners.
  • No built-in TypeScript support; works with CommonJS compiled from TS, but type safety is lost across __set__/__get__ boundaries.

When to avoid it — and what to weigh

  • Project uses ES modules (ESM) extensively — Rewire only supports CommonJS. Babel transpilation of ESM to CJS causes variable renaming that breaks rewire's injection. Consider babel-plugin-rewire for Babel workflows.
  • Module exports a primitive value — Rewire cannot attach __set__, __get__, __with__ to primitives (numbers, strings, booleans). Module structure must export an object or function.
  • Testing complex, idempotent-sensitive modules (e.g., Mongoose models) — Rewire re-executes the module on each call, which can trigger side effects or registration conflicts in libraries expecting singleton behavior.
  • Lazy or deferred global mutations matter — Globals are captured into module scope at rewire() time; later changes to global object properties are not reflected. Incompatible with sinon fake timers applied after rewire().

License & commercial use

MIT License. Permissive OSI-approved license allowing unrestricted use, modification, and distribution in commercial and private projects. No copyleft obligations.

MIT license permits commercial use with no restrictions. Rewire is development/test-time tooling only—no runtime exposure in production artifacts. No license review required for commercial deployment, but verify your test infrastructure and CI/CD pipeline comply with any organizational policies.

DEV.co evaluation signals

Editorial assessment — not user reviews. Directional, with an explicit confidence level.

SignalAssessment
MaintenanceActive
DocumentationAdequate
License clarityClear
Deployment complexityLow
DEV.co fitGood
Assessment confidenceHigh
Security considerations

Rewire uses eval() to implement variable assignment. This is eval of user-controlled test code in a controlled test environment; not a production security risk. However, avoid passing untrusted input to __set__/__get__ in test logic. No credential handling or network exposure. Ensure test files are not accessible in production.

Alternatives to consider

Sinon.JS (stubs/spies)

Provides targeted stubbing of methods and spies without module-level rewiring. Lighter-weight for most use cases; works with ESM. Less intrusive but requires strategic injection points.

Jest moduleNameMapper + jest.mock()

Jest's native mocking avoids rewire entirely if using Jest. Hoisting and automatic mocking of dependencies; better ESM support. Tight coupling to Jest; less portable.

babel-plugin-rewire

Companion Babel plugin enabling rewire-like behavior in transpiled ES modules. Bridges ESM gap but adds build complexity and requires Babel infrastructure.

Software development agency

Build on rewire with DEV.co software developers

Rewire simplifies CommonJS module testing through dependency isolation and state injection. Ideal for teams standardizing on Node.js testing practices. Need guidance on integrating rewire into your CI/CD pipeline or choosing between rewire and Jest mocking? Contact our software engineering team.

Talk to DEV.co

Related open-source tools

Surfaced by semantic similarity across the DEV.co open-source index.

Related on DEV.co

Explore the category and the services that help you build with it.

rewire FAQ

Can I use rewire with ES modules?
No. Rewire requires CommonJS. If your source is ESM and transpiled via Babel, variable renaming breaks rewire. Consider babel-plugin-rewire or refactoring to dependency injection.
Does rewire work with Jest?
Yes. Rewire works as a dev dependency in Jest projects. However, Jest's native jest.mock() and moduleNameMapper often suffice and avoid rewire's globals-capture timing issue.
Why does rewire re-execute my module every time?
Each rewire() call creates a fresh instance to isolate test state. If module side effects (e.g., Mongoose model registration) occur, use caching or refactor the module.
Can I rewire variables inside functions?
No. JavaScript's lexical scoping prevents runtime rewiring of function-local variables. Only module-level scope and globals are accessible.

Software development & web development with DEV.co

From first prototype to production, DEV.co delivers software development services around tools like rewire. Our software development agency staffs experienced software developers and web developers for custom software development, web development, integrations, and ongoing support across open-source testing and beyond.

Integrate Rewire into Your Test Suite

Rewire simplifies CommonJS module testing through dependency isolation and state injection. Ideal for teams standardizing on Node.js testing practices. Need guidance on integrating rewire into your CI/CD pipeline or choosing between rewire and Jest mocking? Contact our software engineering team.