Gathering detailed insights and metrics for rewire
Gathering detailed insights and metrics for rewire
Gathering detailed insights and metrics for rewire
Gathering detailed insights and metrics for rewire
npm install rewire
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,080 Stars
324 Commits
128 Forks
27 Watching
2 Branches
23 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
JavaScript (99.82%)
TypeScript (0.18%)
Cumulative downloads
Total Downloads
Last day
-16.3%
68,185
Compared to previous day
Last week
0.4%
423,922
Compared to previous week
Last month
14.4%
1,674,123
Compared to previous month
Last year
8.9%
19,381,683
Compared to previous year
1
7
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
process
Please note: The current version of rewire is only compatible with CommonJS modules. See Limitations.
npm install rewire
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
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.
Returns a rewired version of the module found at filename
. Use rewire()
exactly like require()
.
Sets the internal variable name
to the given value
. Returns a function which can be called to revert the change.
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.
Returns the private variable with the given name
.
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.
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.
See rewire-webpack
MIT
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
all dependencies are pinned
Details
Reason
license file detected
Details
Reason
3 existing vulnerabilities detected
Details
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
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
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 More