![Introducing Enhanced Alert Actions and Triage Functionality](https://cdn.sanity.io/images/cgdhsj6q/production/fe71306d515f85de6139b46745ea7180362324f0-2530x946.png?w=800&fit=max&auto=format)
Product
Introducing Enhanced Alert Actions and Triage Functionality
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
rewire
Advanced tools
Package description
Rewire is a testing utility for Node.js that allows you to modify the behavior of a module by overriding its private variables and functions. This is particularly useful for unit testing, as it enables you to test private functions and mock dependencies.
Accessing Private Variables
This feature allows you to access private variables within a module. In the code sample, `privateVar` is a private variable in `myModule` that is accessed using `__get__`.
const rewire = require('rewire');
const myModule = rewire('./myModule');
const privateVar = myModule.__get__('privateVar');
console.log(privateVar);
Mocking Private Functions
This feature allows you to mock private functions within a module. In the code sample, `privateFunction` is a private function in `myModule` that is mocked using `__set__`.
const rewire = require('rewire');
const myModule = rewire('./myModule');
myModule.__set__('privateFunction', function() { return 'mocked'; });
console.log(myModule.somePublicFunction());
Mocking Dependencies
This feature allows you to mock dependencies of a module. In the code sample, `dependency` is a dependency of `myModule` that is mocked using `__set__`.
const rewire = require('rewire');
const myModule = rewire('./myModule');
myModule.__set__('dependency', { someMethod: () => 'mocked' });
console.log(myModule.somePublicFunction());
Proxyquire is a module that allows you to override dependencies during testing. Unlike Rewire, which focuses on accessing and modifying private variables and functions, Proxyquire is more about replacing entire dependencies with mocks or stubs.
Sinon is a testing library that provides standalone test spies, stubs, and mocks. While it doesn't allow you to access private variables directly like Rewire, it is very powerful for creating mocks and stubs for functions and objects.
Testdouble is a library for creating test doubles (mocks, stubs, etc.). It focuses on providing a clean and simple API for creating test doubles, but it doesn't provide the ability to access or modify private variables like Rewire.
Readme
Easy dependency injection for node.js unit testing.
rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may
process
rewire does not load the file and eval the contents to emulate node's require mechanism. In fact it uses node's own require to load the module. Thus your module behaves exactly the same in your test environment as under regular circumstances (except your modifications).
Good news to all caffeine-addicts: rewire works also with Coffee-Script. Note that in this case CoffeeScript needs to be listed in your devDependencies.
If you want to use rewire also on the client-side take a look at client-side bundlers
Imagine you want to test this module:
lib/myModule.js
// With rewire you can change all these variables
var fs = require("fs"),
path = "/somewhere/on/the/disk";
function readSomethingFromFileSystem(cb) {
console.log("Reading from file system ...");
fs.readFile(path, "utf8", cb);
}
exports.readSomethingFromFileSystem = readSomethingFromFileSystem;
Now within your test module:
test/myModule.test.js
var rewire = require("rewire");
var myModule = rewire("../lib/myModule.js");
rewire acts exactly like require. Just with one difference: Your module will now export a special setter and getter for private variables.
myModule.__set__("path", "/dev/null");
myModule.__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.
var fsMock = {
readFile: function (path, encoding, cb) {
expect(path).to.equal("/somewhere/on/the/disk");
cb(null, "Success!");
}
};
myModule.__set__("fs", fsMock);
myModule.readSomethingFromFileSystem(function (err, data) {
console.log(data); // = Success!
});
You can also set multiple variables with one call.
myModule.__set__({
fs: fsMock,
path: "/dev/null"
});
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.
myModule.__set__({
console: {
log: function () { /* be quiet */ }
},
process: {
argv: ["testArg1", "testArg2"]
}
});
__set__
returns a function which reverts the changes introduced by this particular __set__
call
var revert = myModule.__set__("port", 3000);
// port is now 3000
revert();
// port is now the previous value
For your convenience you can also use the __with__
method which reverts the given changes after it finished.
myModule.__with__({
port: 3000
})(function () {
// within this function port is 3000
});
// 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.
myModule.__with__({
port: 3000
})(function () {
return new Promise(...);
}).then(function () {
// now port is the previous value again
});
// port is still 3000 here because the promise hasn't been resolved yet
Difference to require()
Every call of rewire() executes the module again and returns a fresh instance.
rewire("./myModule.js") === rewire("./myModule.js"); // = false
This can especially be a problem if the module is not idempotent like mongoose models.
Changing globals
Be careful, if you do something like this you'll change your global console instance.
myModule.__set__("console.log", function () { /* be quiet */ });
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.
##Client-Side Bundlers
###webpack See rewire-webpack
###browserify If you're using browserify and want to use rewire with browserify please let me know.
##License
MIT
FAQs
Easy dependency injection for node.js unit testing
The npm package rewire receives a total of 402,496 weekly downloads. As such, rewire popularity was classified as popular.
We found that rewire demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.