Installations
npm install rewire
Developer
jhnns
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
18.16.0
NPM Version
9.5.1
Statistics
3,082 Stars
324 Commits
128 Forks
27 Watching
2 Branches
23 Contributors
Updated on 28 Oct 2024
Languages
JavaScript (99.82%)
TypeScript (0.18%)
Total Downloads
Cumulative downloads
Total Downloads
99,588,921
Last day
-5.1%
74,336
Compared to previous day
Last week
2.9%
437,191
Compared to previous week
Last month
17.6%
1,666,698
Compared to previous month
Last year
9.1%
19,391,335
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
7
rewire
Easy monkey-patching for node.js unit tests
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:
1// lib/myModule.js 2// With rewire you can change all these variables 3var fs = require("fs"), 4 path = "/somewhere/on/the/disk"; 5 6function readSomethingFromFileSystem(cb) { 7 console.log("Reading from file system ..."); 8 fs.readFile(path, "utf8", cb); 9} 10 11exports.readSomethingFromFileSystem = readSomethingFromFileSystem;
Now within your test module:
1// test/myModule.test.js 2var rewire = require("rewire"); 3 4var 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.
1myModule.__set__("path", "/dev/null"); 2myModule.__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.
1var fsMock = { 2 readFile: function (path, encoding, cb) { 3 expect(path).to.equal("/somewhere/on/the/disk"); 4 cb(null, "Success!"); 5 } 6}; 7myModule.__set__("fs", fsMock); 8 9myModule.readSomethingFromFileSystem(function (err, data) { 10 console.log(data); // = Success! 11});
You can also set multiple variables with one call.
1myModule.__set__({ 2 fs: fsMock, 3 path: "/dev/null" 4});
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.
1myModule.__set__({ 2 console: { 3 log: function () { /* be quiet */ } 4 }, 5 process: { 6 argv: ["testArg1", "testArg2"] 7 } 8});
__set__
returns a function which reverts the changes introduced by this particular __set__
call
1var revert = myModule.__set__("port", 3000); 2 3// port is now 3000 4revert(); 5// port is now the previous value
For your convenience you can also use the __with__
method which reverts the given changes after it finished.
1myModule.__with__({ 2 port: 3000 3})(function () { 4 // within this function port is 3000 5}); 6// 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.
1myModule.__with__({ 2 port: 3000 3})(function () { 4 return new Promise(...); 5}).then(function () { 6 // now port is the previous value again 7}); 8// 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.
1// myModule.js 2(function () { 3 // Can't be changed by rewire 4 var someVariable; 5})()
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.
1// Will throw an error if it's loaded with rewire() 2module.exports = 2;
Globals with invalid variable names
rewire imports global variables into the local scope by prepending a list of var
declarations:
1var 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.
1rewire("./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:
1myModule.__set__("console", { 2 log: function () {} 3});
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
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
all dependencies are pinned
Details
- Info: 3 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 2 out of 2 third-party GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
3 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
Reason
Found 6/20 approved changesets -- score normalized to 3
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 16 are checked with a SAST tool
Score
4.1
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to rewire
@types/rewire
TypeScript definitions for rewire
babel-plugin-rewire
A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.
@juanger/babel-plugin-rewire-ts
A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.
babel-plugin-rewire-ts
A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.