Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
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.
Dependency injection for node.js applications.
rewire allows you to modify the behaviour of modules for better unit testing. You may
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).
Debugging is fully supported.
npm install rewire
var rewire = require("rewire"),
rewiredModule;
// Default
////////////////////////////////
// rewire acts exactly like require when omitting all other params
rewire("./myModuleA.js") === require("./myModuleA.js"); // = true
// Mocks
////////////////////////////////
var mockedModuleB = {},
mockedFs = {},
mocks = {
"fs": mockedFs,
"path/to/moduleB.js": mockedModuleB
};
// The rewired module will now use your mocks instead of fs and moduleB.js.
// Just make sure that the path is exactly as in myModuleA.js required.
rewiredModule = rewire("./myModuleA.js", mocks);
// Injections
////////////////////////////////
var injections = {
console: {
log: function () { /* be quiet */ }
},
process: { argv: ["someArgs"] },
__filename: "some/other/dir"
};
// This will inject
// var console = {log: function () { /* be quiet */ }};
// var process = {argv: ["someArgs"] };
// var __filename = "some/other/dir";
// at the bottom of the module.
// This way you can override private variables within the module
rewiredModule = rewire("./myModuleA.js", null, injections);
// You can also pass a script to inject
rewiredModule = rewire("./myModuleA.js", null, "console.log('hellooo');"); // prints "hellooo"
// Leaks
////////////////////////////////
var leaks = ["myPrivateVar1", "myPrivateVar2"];
// rewire exports variables under the special "__"-object.
rewiredModule = rewire("./myModuleA.js", null, null, leaks);
rewiredModule.__.myPrivateVar1; // returns former private myPrivateVar1
rewiredModule.__.myPrivateVar2; // returns former private myPrivateVar2
// Cache
////////////////////////////////
// By disabling the module cache the rewired module will not be cached.
// Any later require()-calls within other modules will now return the original
// module again instead of the rewired. Caching is enabled by default.
rewire("./myModuleA.js", null, null, null, false) !== require("./myModuleA.js"); // = true
##API
rewire(filename, mocks, injections, leaks, cache)
require("../../myModules/myModuleA.js")
you need to pass {"../../myModules/myModuleA.js": myModuleAMock}
.var
s within the module. You can also eval a string. Please note: All scripts are injected at the end of the module. So if there is any code in your module that is executed during require()
, your injected variables will be undefined at this point. For example: passing {console: null}
will cause all calls of console.log()
to throw an exception if they're executed during require()
.myModule.__
require()
will return the rewired module. Further calls of rewire()
will always overwrite the cache.This module is inspired by the great injectr-module.
(The MIT License)
Copyright (c) 2012 Johannes Ewald <mail@johannesewald.de>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Easy dependency injection for node.js unit testing
The npm package rewire receives a total of 353,877 weekly downloads. As such, rewire popularity was classified as popular.
We found that rewire demonstrated a not healthy version release cadence and project activity because the last version was released 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.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.