Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
rewiremock
Advanced tools
/$$ /$$ /$$ /$$ /$$ /$$
| $$ /$ | $$|__/ | $$$ /$$$ | $$
/$$$$$$ /$$$$$$ | $$ /$$$| $$ /$$ /$$$$$$ /$$$$$$ | $$$$ /$$$$ /$$$$$$ /$$$$$$$| $$ /$$
/$$__ $$ /$$__ $$| $$/$$ $$ $$| $$ /$$__ $$ /$$__ $$| $$ $$/$$ $$ /$$__ $$ /$$_____/| $$ /$$/
| $$ \__/| $$$$$$$$| $$$$_ $$$$| $$| $$ \__/| $$$$$$$$| $$ $$$| $$| $$ \ $$| $$ | $$$$$$/
| $$ | $$_____/| $$$/ \ $$$| $$| $$ | $$_____/| $$\ $ | $$| $$ | $$| $$ | $$_ $$
| $$ | $$$$$$$| $$/ \ $$| $$| $$ | $$$$$$$| $$ \/ | $$| $$$$$$/| $$$$$$$| $$ \ $$
|__/ \_______/|__/ \__/|__/|__/ \_______/|__/ |__/ \______/ \_______/|__/ \__/
Dependency mocking, inspired by the best libraries:
rewiremock
is a better mockery
, with the same interface.rewiremock
is a better proxyquire
, with the same interface.rewiremock
is not.Jest
is awesome. As well as rewiremock
.Rewiremock is a better version of your favorite library__. For mocha
, ava
, karma
, and anything not-jest
.
By desing rewiremock has same behavior as Mockery. But it can behave like other libraries too, exposing handly interfaces to make mocking a joy. Support type-safe mocking and provides TS/Flow types for itself.
yarn add --dev rewiremock
or npm i --save-dev rewiremock
I would recoment not to import rewiremock
directly in tests, but create rewiremock.js
and require it - that would let you to tune rewiremock, if you need it.
import
// rewiremock.es6.js
import rewiremock from 'rewiremock';
/// settings
rewiremock.overrideEntryPoint(module); // this is important
export { rewiremock }
require('rewiremock/node')
// rewiremock.cjs.js
const rewiremock = require 'rewiremock/node';
/// settings
rewiremock.overrideEntryPoint(module); // this is important
module.exports = rewiremock;
// rewiremock.es6.js
import rewiremock from 'rewiremock/webpack';
/// settings
rewiremock.overrideEntryPoint(module); // this is important
export { rewiremock }
If you import
rewiremock
dirrectly from your tests - you dont needoverrideEntryPoint
There are 3 ways to mock, all with some pros and cons.
Simplest one.
const file = rewiremock.proxy('file.js', {
'dependency': stub
});
// or
const file = rewiremock.proxy(() => require('file.js'), {
'dependency': stub
});
Most powerfull one
rewiremock('dependency').with(stub);
rewiremock(() => require('dependency')).with(stub);
rewiremock.enable();
const file = require('file.js');
rewiremock.disable();
Shortest one
// just place it next to `imports` and add a rewiremock/babel plugin
rewiremock('dependency').with(stub);
There is a plenty of plugins to make your life easier. For example - this is my favorite setup
import { resolve } from 'path';
import rewiremock, { addPlugin, overrideEntryPoint, plugins } from 'rewiremock';
import { configure } from 'rewiremock/lib/plugins/webpack-alias'; // could be better
configure(resolve(`${__dirname}/../../webpack.config.test.js`));
overrideEntryPoint(module);
// we need webpack aliases
addPlugin(plugins.webpackAlias);
// and all stub names would be a relative
addPlugin(plugins.relative);
// and all stubs should be used. Lets make it default!
addPlugin(plugins.usedByDefault);
export { rewiremock };
// use `require` instead of just filename to maintain type information
const mock = rewiremock.proxy(() => require('somemodule'), r => {
'dep1': { name: 'override' },
// use all power of rewiremock to mock something as you want...
'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly(), // use all `mocking API`
}));
There is two important things here:
require
or import
to specify file to require and file to mock. This helps to resolve file names and maintain type information(if you have it). See Guided Mocking
bellow..proxy
) and the main API.In case to support ESM modules(powered by @std/ESM, not native modules) you have to use import
command.
.module
- an "async" version of .proxy
const mock = await rewiremock.module(() => import('somemodule'), {...});
import
- that wouldrewiremock(() => require('xxx').with({});
rewiremock('yyy').with({});
const file = await import('somemodule');
Ok! Let's move forward!
rewiremock.enable()
- wipes cache and enables interceptor.rewiremock.disable()
- wipes cache and disables interceptor.rewiremock.around(loader, creator):Promise< T >
- loads a module in an asynchronous sandbox.rewiremock.proxy(file, stubs):T
- proxyquire like mocking api, where file is file name, and stubs are an object or a function.rewiremock.module(loader, stubs):Promise< T >
- async version of proxy, where loader is a function.rewiremock(moduleName: string)
- fabric for a moduleNames's mockrewiremock(moduleImport: loader)
- async fabric for a module import function.
.enable/disable()
- to enable or disable mock (enabled by default)..with(stubs: function | Object)
- overloads module with a value.withDefault(stub: function | Object)
- overload default
es6 export.es6()
- marks module as ES6( __esModule ).by(otherModule: string| function)
- overload by another module(if string provider) or by result of a function call..callThrough()
- first load the original module, and next extend it by provided stub..mockThrough([stubFactory])
- first load the original module, and then replaces all exports by stubs..dynamic()
- enables hot mock updates..toBeUsed()
- enables usage checking..directChildOnly
- will do mock only direct dependencies..calledFromMock
- will do mock only dependencies of mocked dependencies.rewiremock.getMock(moduleName: string|loader)
- returns existing mock (rewiremock(moduleName) will override)rewiremock.isolation()
- enables isolationrewiremock.withoutIsolation()
- disables isolationrewiremock.passBy(pattern or function)
- enables some modules to pass throught isolation.rewiremock.inScope(callback)
- place synchronous callback inside a sandbox.rewiremock.stubFactory(factory)
- define a stub factory for mockThrough command.Rewiremock supports (inspired by Jest) auto __mocks__
ing.
Just create __mocks__/fileName.js
, and fileName.js
will be replaced by mock. Please refer to Jest documentation for use cases.
If you dont want some file to be replaced by mock - add it, and then - disable
rewiremock('fileName.js').disable();
Yep - there is 4 top level ways to activate a mock - inScope
, around
, proxy
or just enable
.
Rewiremock provides lots of APIs to help you setup mock, and get the mocked module.
All the mocks await you to provide "stubs" to override the real implimentation. If you want just to ensure you have called endpoints – use rewiremock('someFile').mockThrough.
proxy
will load a file by it's own ( keep in mind - name resolution is a complex thing)const mock = rewiremock.proxy('somemodule', (r) => ({
'dep1': { name: 'override' },
'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly(), // use all `mocking API`
'dep3': r.mockThrough() // automatically create a test double
}));
const mock = rewiremock.proxy(() => require('somemodule'), {
'dep1': { name: 'override' },
'dep2': { onlyDump: 'stubs' }
}));
import
(not for node.js mjs real
es6 modules)
module
is an async version of proxy, so you can use importsconst mock = await rewiremock.module(() => import('somemodule'), {
'dep1': { name: 'override' },
'dep2': { onlyDump: 'stubs' }
}));
around
- another version of .module, where you can do just const mock = await rewiremock.around(() => import('somemodule'), () => {
rewiremock('dep1').with('something');
callMom();
// prepare mocking behavior
}));
enable
/disable
- Low level API rewiremock('someThing').with('someThingElse')
rewiremock.enable();
// require something
rewiremock.disable();
In all the cases you can specify what exactly you want to mock, or just mock anything
addPlugin(plugins.mockThroughByDefault);
You can also use a top level mocking, the same as Jest could only provide
import sinon from 'sinon';
import rewiremock from 'rewiremock';
import Component1 from 'common/Component1';
import selectors from 'common/selectors';
rewiremock('common/Component1').by('common/Component2');
rewiremock('common/Component2/action').with({ action: () => {} });
rewiremock('common/selectors').mockThrough(() => sinon.stub());
selectors.findUser.returns("cat"); // this is sinon stub.
As result Component1 will be replaced by Component2, action with empty function and all selectors by sinon stubs, with one configured.
This is only possible via babel plugin, and without it this code will be executed without any sence, as long mocking will be configured after the files required.
rewiremock/babel
into plugin section in .babelrc
// .babelrc
{
"presets": [
//.....
],
"plugins": [
"rewiremock/babel"
]
}
import sinon from 'sinon';
import rewiremock from 'rewiremock';
rewiremock('common/Component1').by('common/Component2');
rewiremock('common/Component2/action').with({ action: () => {} });
rewiremock('common/selectors').mockThrough(() => sinon.stub());
rewiremock('common/Component2/React').withDefault(ComponentMock);
// "function" would be hoisted by js itself
function ComponentMock({children}) { return <div>mock!</div>; }
rewiremock.enabled();
import Component1 from 'common/Component1';
import selectors from 'common/selectors';
rewiremock.disable();
selectors.findUser.returns("cat"); // this is sinon stub.
Keep in mind - rewiremock will hoist mock definition next to rewiremock import.
It is possible to partially change mocking already being applied.
rewiremock('./foo')
.callThrough()
.with({ action1: action1Stub1 })
.dynamic();
const foo = require('./foo');
foo.action == action1Stub1;
rewiremock.getMock('./foo')
.with({ action1: action1Stub2 });
//while will RESET the mock, and could not change existing ones.
rewiremock('./foo')
.with({ action1: action1Stub2 });
foo.action == action1Stub2;
rewiremock('./foo')
.with({ });
foo.action == theRealFoo;
import rewiremock from 'rewiremock';
import foo from './foo';
rewiremock('./foo')
.with({ action1: action1Stub1 })
.dynamic();
const fooMock = rewiremock.getMock('./foo');
describe(..., () => {
it('...', () => {
fooMock.with({ });
// while may NOT found the mock
rewiremock.getMock('./foo').with({ });
});
})
You may use require
or import
to let IDE help you to properly write fileName,
and hide all filename resolution and transformation behind the scenes.
But there are things you have to keep in mind
rewiremock(() => require('./fileToMock1')); // this mock would work
rewiremock.enable();
rewiremock(() => require('./fileToMock2')); //this mock WOULD NOT WORK!
rewiremock(() => import('./fileToMock1'));
rewiremock.enable(); // this is an exception
rewiremock.module( () => import('file')) // this is ok
rewiremock.around(..., rw => rw.mock(() => import('file2'))) // this is ok
Rewiremock is able to provide a type-safe mocks. To enable type-safety follow these steps:
// @flow
import rewiremock from 'rewiremock';
rewiremock.around(
() => import('./a.js'),
mock => {
mock(() => import('./b.js'))
.withDefault(() => "4")
.with({testB: () => 10})
.nonStrict() // turn off type system
.with({ absolutely: "anything" })
}
);
If default export is not exists on module 'b', or there is no named export testB, or types do not match - type system will throw.
If you will declare an async mock, you it will not be resolved by the time of execution - Rewiremock will throw on Error.
If you have async imports inside mocked file, follow this syntax
rewiremock.around(
() => import('./a.js'),
mock => {
// just before loader function rewiremock enabled itself
mock(() => import('./b.js').then(mock=>mock)) // mocks `live` one `tick` more
// just after loader function resolved rewiremock disables itself
mock => {
....
}
}
);
Rewiremock can check mock against the real implementation. This does not perform type checking
, but
could check exported names and exported types (function vs number, for example).
Rewiremock expects that mock will be less or equal than original file.
rewiremock: mocked export "somethingMissing" does not exists in ./b.js
rewiremock: exported type mismatch: ./b.js:default. Expected function, got number
To activate exports comparison
rewiremock('somemoduname')
.toMatchOrigin(); // to activate
// or
import rewiremock, { addPlugin, removePlugin, plugins } from 'rewiremock';
addPlugin(plugins.alwaysMatchOrigin);
Just use it. You can also activate nodejs, which will double check all modules names on a real FS, but.. everything might work out of the box.
PS: Just use usedByDefault to ensure module names are resolved correctly.
There is also a special entry point for node.js, with nodejs plugin activated, and rewiremock as es5 export
const rewiremock = require('rewiremock/node');
// meanwhile
const rewiremock = require('rewiremock').default;
Rewiremock can emulate
few webpack features(like aliases) in node.js environment, but it also can be run inside webpack.
Actually rewiremock is the first client side mocking library
But not so fast, hanny. First you have to have 3(!) Plugins enabled.
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new (require("rewiremock/webpack/plugin"))()
]
That's all. Now all magic will happens at client side.
It is better to use .proxy/module command with direct require/import and leave all names conversion to webpack.
For better dev experience include special configuration of webpack
import rewiremock from 'rewiremock/webpack';
Currently there are 2 known problems, both for mocha+webpack, ie using nodejs to run webpack bundle:
TypeError: Cannot read property 'webpackHotUpdate' of undefined
Caused by babel. Just dont use babel then running webpack bundles. Use babel them creating bundled.
TypeError: Cannot read property 'call' of undefined
Caused by webpack. Sometimes is does not include some important files.
To solve this problem just import('rewiremock/webpack/interceptor')
in scaffolding.
The problem is simply - this file does not exists in the bundle.
First - define your mocks. You can do it in any place, this is just a setup.
import rewiremock from 'rewiremock';
...
// totaly mock `fs` with your stub
rewiremock('fs')
.with({
readFile: yourFunction
});
// replace path, by other module
rewiremock('path')
.by('path-mock');
// replace enzyme by preconfigured one (from https://medium.com/airbnb-engineering/unlocking-test-performance-migrating-from-mocha-to-jest-2796c508ec50)
rewiremock('enzyme')
.by(({requireActual}) => {
// see rest of possible params in d.ts file
const enzyme = requireActual('enzyme');
if (!mockSetup) {
const chai = requireActual('chai');
const chaiEnzyme = requireActual('chai-enzyme');
chai.use(chaiEnzyme());
}
return enzyme;
});
// replace default export of ES6 module
rewiremock('reactComponent')
.withDefault(MockedComponent)
// replace only part of some library and keep the rest
rewiremock('someLibrary')
.callThrough()
.with({
onlyOneMethod
})
// secure yourself and from 'unexpected' mocks
rewiremock('myDep')
.with(mockedDep)
.calledFromMock()
There is a simply way to do it: Just enable it, and dont forget to disable it later.
//in mocha tests
beforeEach( () => rewiremock.enable() );
//...
// here you will get some advantage in type casting and autocompleting.
// it will actually works...
const someModule = require('someModule');
//...
afterEach( () => rewiremock.disable() );
Once enabled, rewiremock will wipe all mocked modules from cache, and all modules which require them.
Including your test.
Once disabled it will restore everything.
All unrelated to test dependencies will be kept. Node modules, react, common files - everything.
As result - it will run faster.
Sometimes you will have independent tests in a single file, and you might need separate mocks for each one.
inScope
execute callback inside sandbox, and all mocks or plugins or anything else you have added will not leaks away.
rewiremock.inScope( () => {
rewiremock('something').with(something);
rewiremock.enable();
// is 'something' mocked? Yes
....
rewiremock.disable();
// is 'something' mocked? No
// is it still listed as mock? Yes
});
// is 'something' mocked or listed? No
And there is a bit harder way to do it - scope. inScope will create new internal scope, next you can add something new to it, and then it will be destroyed. It will also enable/disable rewiremock just in time.
This helps keep tests in isolation.
PS: scopes are nesting each other like javascript prototypes do.
rewiremock.around(
() => import('somemodule'), // load a module. Using import or require.
// just before it you can specify mocks or anything else
(mock) => {
addPlugin(nodePlugin);
mock('./lib/a/foo').with(() => 'aa');
mock('./lib/a/../b/bar').with(() => 'bb');
mock('./lib/a/../b/baz').with(() => 'cc');
}
) // at this point scope is dead
.then((mockedBaz) => {
expect(mockedBaz()).to.be.equal('aabbcc');
});
or just
rewiremock.around(() => import('somemodule')).then(mockedModule => doSomething)
or
rewiremock.around(
() => import('somemodule').then( mockedModule => doSomething),
(mock) => aPromise
);
Currently .inScope is the only API capable to handle es6(not node [m]js!) dynamic imports.
Sometimes it is much easier to combine all the things together.
// preferred way - crete stubs using a function, where R is mock creator
rewiremock.proxy('somemodule', (r) => ({
'dep1': { name: 'override' },
'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly() // same powerfull syntax
}));
// straight way - just provide stubs.
rewiremock.proxy('somemodule', {
'dep1': { name: 'override' },
'dep2': { name: 'override' }
}));
By default - rewiremock has limited features. You can extend its behavior via plugins.
usual
node.js application. Will absolutize all paths. Will wipe cache very accurately.import rewiremock, { addPlugin, removePlugin, plugins } from 'rewiremock';
addPlugin(plugins.webpackAlias);
removePlugin(plugins.webpackAlias);
If you import rewiremock from other place, for example to add some defaults mocks - it will not gonna work. Each instance of rewiremock in independent. You have to pass your instance of rewiremock to build a library. PS: note, rewiremock did have nested API, but it were removed.
Unit testing requires all dependencies to be mocked. All! To enable it, run
rewiremock.isolation();
//or
rewiremock.withoutIsolation();
Then active - rewiremock will throw error on require of any unknown module.
Unknown is module which is nor mocked, nor marked as pass-through.
To make few modules to be invisible
to rewiremock, run
rewiremock.passBy(/*pattern or function*/);
rewiremock.passBy(/common/);
rewiremock.passBy(/React/);
rewiremock.passBy(/node_modules/);
rewiremock.passBy((name) => name.indexOf('.node')>=0 )
Sometimes you have to be sure, that you mock is actually was called.
Isolation will protect you then you add new dependencies, .toBeUsed
protect you from removal.
Jest is a very popular testing framework, but it has one issue - is already contain mocking support.
Do not use rewiremock and jest. Even if it is possible.
To use rewiremock with Jest add to the beginning of your file
// better to disable automock
jest.disableAutomock();
// Jest breaks the rules, and you have to restore nesting of a modules.
rewiremock.overrideEntryPoint(module);
// There is no way to use overload by Jest require or requireActual.
// use the version provided by rewiremock.
require = rewiremock.requireActual;
!!! the last line here may disable Jest sandboxing. !!!
Also it will disable Jest transformation, killing all the jest magics.
To be able continue use ES6/imports - you have to enforce Babel to be applied in the common
way.
describe('block of tests', () => {
// require babel-register in describe or it block.
// NOT! On top level. Jest sandboxing and isolation are still in action,
// and will reset all settings to default
require("babel-register");
})
PS: Jest will set BABEL_ENV to test
.
It is better just to use rewiremock.requireActual
, without overriding global require.
In most cases you have to:
And it is not a good idea to do it in every test you have.
It is better to have one setup file, which will do everything for you
// this is your test file
// instead of importing original file - import your own one
// import rewiremock from 'rewiremock';
import rewiremock from 'test/rewiremock';
// this tests/rewiremock.js
import rewiremock, { addPlugin, overrideEntryPoint} from 'rewiremock';
// do anything you need
addPlugin(something);
rewiremock('somemodule').with(/*....*/);
// but don't forget to add some magic
overrideEntryPoint(module); // <-- set yourself as top module
// PS: rewiremock will wipe this module from cache to keep magic alive.
export default rewiremock;
Absolutely the same - preconfiguring rewiremock one can achive via default configuration.
Just put rewiremock.config.js in the root dir, next to project.json, and export a configuration function
// rewiremock.config.js
import wrongrewiremock, {plugins} from 'rewiremock';
export default rewiremock => {
// do everything with "right" rewiremock
rewiremock.addPlugin(plugins.nodejs)
}
Default cache policy follow these steps:
forceCacheClear
mode is set.The last variant is default for proxyquire and mockery, also it is more sequre
from different side effects.
Regardless, default is the first variant - as a way faster, and secure enough.
As result of this mocking strategy you can mock any file at any level, while keeping another files cached.
If you don't want this - just add relative
plugin. It will allow mocking only for modules
required from module with parent equals entryPoint.
PS: module with parent equals entryPoint - any module you require from test(it is an entry point). required from that module - first level require. Simple.
Don't forget - you can write your own plugins. plugin is an object with fields:
{
// to transform name. Used by alias or node.js module
fileNameTransformer: (fileName, parentModule) => fileName;
// check should you wipe module or not. Never used :)
wipeCheck: (stubs, moduleName) => boolean,
// check is mocking allowed for a module. User in relative plugin
shouldMock: (mock, requestFilename, parentModule, entryPoint) => boolean
}
Rewiremock will automatically try to resolve file
import {resolveExtensions} from 'rewiremock';
resolveExtensions(['.wasm', '.mjs', '.js', '.json']);
resolveExtensions
is quite similar to webpack's resolve extensions.
If something is not working - just check that you:
Rewiremock - medium article all by tag
MIT
Happy mocking!
FAQs
Advanced dependency mocking device.
The npm package rewiremock receives a total of 45,162 weekly downloads. As such, rewiremock popularity was classified as popular.
We found that rewiremock demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer 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.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.