Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

rewiremock

Package Overview
Dependencies
Maintainers
1
Versions
71
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rewiremock - npm Package Compare versions

Comparing version 2.0.0 to 2.1.0

lib/module.js

205

lib/executor.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.originalLoader = undefined;
exports.requireModule = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _module = require('module');
var _path = require('path');
var _module = require('./module');
var _module2 = _interopRequireDefault(_module);

@@ -24,118 +26,143 @@

var originalLoader = exports.originalLoader = _module2.default._load;
var thisModule = module;
var patternMatch = function patternMatch(fileName) {
return function (pattern) {
if (typeof pattern == 'function') {
return pattern(fileName);
}
return fileName.match(pattern);
};
return function (pattern) {
if (typeof pattern == 'function') {
return pattern(fileName);
}
return fileName.match(pattern);
};
};
var requireModule = exports.requireModule = function requireModule(name) {
if (typeof __webpack_require__ !== 'undefined') {
return __webpack_require__(name);
} else {
return require(name);
}
};
var testPassby = function testPassby(request, module) {
var _getScope = (0, _globals2.default)(),
parentModule = _getScope.parentModule,
passBy = _getScope.passBy,
mockedModules = _getScope.mockedModules,
isolation = _getScope.isolation;
var _getScope = (0, _globals2.default)(),
parentModule = _getScope.parentModule,
passBy = _getScope.passBy,
mockedModules = _getScope.mockedModules,
isolation = _getScope.isolation;
// was called from test
// was called from test
if (module === parentModule || module == module.parent) {
return true;
if ((0, _module.moduleCompare)(module, parentModule)) {
//if (module === parentModule || module == module.parent) {
return true;
}
// if parent is in the pass list - pass everything
var fileName = _module2.default._resolveFilename(request, module);
var m = module;
var test = function test(fileName) {
return !isolation.noAutoPassBy && mockedModules[fileName] || // parent was mocked
passBy.filter(patternMatch(fileName)).length // parent is in pass list
;
};
while (m) {
if (test(fileName)) {
return true;
}
// if parent is in the pass list - pass everything
var fileName = _module2.default._resolveFilename(request, module);
var m = module;
while (m) {
if (!isolation.noAutoPassBy && mockedModules[fileName] || // parent was mocked
passBy.filter(patternMatch(fileName)).length // parent is in pass list
) {
return true;
}
fileName = m.filename;
m = m.parent;
}
return false;
fileName = (0, _module.getModuleName)(m);
m = (0, _module.getModuleParent)(m);
}
return test(fileName);
};
function mockResult(name, data) {
return data;
if (!data.default) {
data.default = data;
}
return data;
}
function monkeyPatchPath(addr) {
var path = addr.split('/');
if (path[0] == '..') {
path[0] = '.';
return path.join('/');
}
return addr;
}
function mockLoader(request, parent, isMain) {
var _getScope2 = (0, _globals2.default)(),
parentModule = _getScope2.parentModule,
mockedModules = _getScope2.mockedModules,
isolation = _getScope2.isolation;
var _getScope2 = (0, _globals2.default)(),
parentModule = _getScope2.parentModule,
mockedModules = _getScope2.mockedModules,
isolation = _getScope2.isolation;
var baseRequest = _module2.default._resolveFilename(request, parent);
var baseRequest = _module2.default._resolveFilename(request, parent);
var shortRequest = monkeyPatchPath((0, _path.relative)((0, _module.getModuleName)(parent), request));
if (parent === parentModule) {
delete _module2.default._cache[baseRequest];
mockedModules[baseRequest] = true;
}
if ((0, _module.moduleCompare)(parent, parentModule) || (0, _module.moduleCompare)(parent, thisModule)) {
delete _module2.default._cache[baseRequest];
mockedModules[baseRequest] = true;
}
var mock = (0, _mocks.getMock)(baseRequest) || (0, _mocks.getMock)(request);
var mock = (0, _mocks.getMock)(baseRequest) || (0, _mocks.getMock)(request) || (0, _mocks.getMock)(shortRequest);
if (mock) {
if ((0, _plugins.shouldMock)(mock, request, parent, parentModule)) {
// this file fill be not cached, but it`s opener - will. And we have to remember it
mockedModules[parent.filename] = true;
mock.usedAs = mock.usedAs || [];
mock.usedAs.push(baseRequest);
if (mock) {
if ((0, _plugins.shouldMock)(mock, request, parent, parentModule)) {
// this file fill be not cached, but it`s opener - will. And we have to remember it
mockedModules[(0, _module.getModuleName)(parent)] = true;
mock.usedAs = mock.usedAs || [];
mock.usedAs.push(baseRequest);
mockedModules[baseRequest] = true;
mockedModules[baseRequest] = true;
if (mock.allowCallThrough) {
if (!mock.original) {
mock.original = originalLoader(request, parent, isMain);
}
}
if (mock.allowCallThrough) {
if (!mock.original) {
mock.original = (0, _module.originalLoader)(request, parent, isMain);
}
}
if (mock.overrideBy) {
if (!mock.override) {
if (typeof mock.overrideBy === 'string') {
mock.override = originalLoader(mock.overrideBy, parent, isMain);
} else {
mock.override = mock.overrideBy({
name: request,
fullName: baseRequest,
parent: parent,
original: mock.original
});
}
}
return mockResult(request, mock.override);
}
if (mock.overrideBy) {
if (!mock.override) {
if (typeof mock.overrideBy === 'string') {
mock.override = (0, _module.originalLoader)((0, _module.pickModuleName)(mock.overrideBy, parent), parent, isMain);
} else {
mock.override = mock.overrideBy({
name: request,
fullName: baseRequest,
parent: parent,
original: mock.original
});
}
}
return mockResult(request, mock.override);
}
if (mock.allowCallThrough) {
if (typeof mock.original === 'function') {
if (_typeof(mock.value) === 'object' && Object.keys(mock.value).length === 0) {
return mockResult(request, mock.original);
} else {
throw new Error('rewiremock: trying to merge Functional base with callThrough mock at ' + request + '. Use overrideBy instead.');
}
}
return mockResult(request, Object.assign({}, mock.original, mock.value, {
__esModule: mock.original.__esModule
}));
}
return mockResult(request, mock.value);
} else {
// why you shouldn't?
if (mock.allowCallThrough) {
if (typeof mock.original === 'function') {
if (_typeof(mock.value) === 'object' && Object.keys(mock.value).length === 0) {
return mockResult(request, mock.original);
} else {
throw new Error('rewiremock: trying to merge Functional base with callThrough mock at ' + request + '. Use overrideBy instead.');
}
}
return mockResult(request, Object.assign({}, mock.original, mock.value, { __esModule: mock.original.__esModule }));
}
return mockResult(request, mock.value);
} else {
// why you shouldn't?
}
}
if (isolation && !mockedModules[baseRequest]) {
if (!testPassby(request, parent)) {
throw new Error('rewiremock: isolation breach by [' + request + ']. Requested from ', parent.filename);
}
if (isolation && !mockedModules[baseRequest]) {
if (!testPassby(request, parent)) {
throw new Error('rewiremock: isolation breach by [' + request + ']. Requested from ', (0, _module.getModuleName)(parent));
}
}
return originalLoader(request, parent, isMain);
return (0, _module.originalLoader)(request, parent, isMain);
}
exports.default = mockLoader;

@@ -12,6 +12,4 @@ 'use strict';

var _wipeNodeCache = require('wipe-node-cache');
var _wipeCache = require('./wipeCache');
var _wipeNodeCache2 = _interopRequireDefault(_wipeNodeCache);
var _plugins = require('./plugins');

@@ -23,2 +21,4 @@

var _module = require('./module');
var _mockModule = require('./mockModule');

@@ -32,3 +32,5 @@

delete require.cache[_path2.default.join(_path2.default.dirname(require.resolve(__filename)), './mockModule.js')];
delete require.cache[_path2.default.join(_path2.default.dirname(__filename), './mockModule.js')];
delete require.cache[(0, _module.getModuleName)(module).replace('index.js', 'mockModule.js')];
var cleanup = exports.cleanup = function cleanup() {

@@ -38,8 +40,8 @@ var wipeAll = function wipeAll(stubs, moduleName) {

};
(0, _wipeNodeCache2.default)(_path2.default.dirname(require.resolve(__filename)), wipeAll);
(0, _wipeCache.wipe)(_path2.default.dirname(__filename), wipeAll);
};
var overrideEntryPoint = exports.overrideEntryPoint = function overrideEntryPoint(module) {
delete require.cache[require.resolve(module.filename)];
API.mockModule.overrideEntryPoint(module.parent);
delete require.cache[(0, _module.getModuleName)(module)];
API.mockModule.overrideEntryPoint((0, _module.getModuleParent)(module));
//API.cleanup();

@@ -57,2 +59,4 @@ };

//addPlugin(plugins.nodejs);
addPlugin(_index2.default.toBeUsed);

@@ -59,0 +63,0 @@ addPlugin(_index2.default.directChild);

@@ -29,10 +29,21 @@ 'use strict';

/**
* Enabled call thought original module
* @name ModuleMock.callThrough
* @return {ModuleMock}
*/
_createClass(ModuleMock, [{
key: 'from',
value: function from(source) {
if (source instanceof ModuleMock) {
var originalName = this.mock.name;
Object.assign(this.mock, source.mock);
this.mock.name = originalName;
} else {
return this.with(source);
}
}
/**
* Enabled call thought original module
* @name ModuleMock.callThrough
* @return {ModuleMock}
*/
_createClass(ModuleMock, [{
}, {
key: 'callThrough',

@@ -158,2 +169,10 @@ value: function callThrough() {

ModuleMock.inlineConstructor = {};
Object.getOwnPropertyNames(ModuleMock.prototype).forEach(function (key) {
ModuleMock.inlineConstructor[key] = function () {
var mock = new ModuleMock({ value: {} });
return mock[key].apply(mock, arguments);
};
});
exports.default = ModuleMock;

@@ -8,3 +8,3 @@ 'use strict';

var _module = require('module');
var _module = require('./module');

@@ -23,6 +23,2 @@ var _module2 = _interopRequireDefault(_module);

var _executor = require('./executor');
var _executor2 = _interopRequireDefault(_executor);
var _plugins = require('./plugins');

@@ -38,3 +34,3 @@

var parentModule = module.parent;
var parentModule = (0, _module.getModuleParent)(module);
var mockScope = null;

@@ -109,3 +105,3 @@ var scope = function scope() {

mockModule.overrideEntryPoint = function (parent) {
mockScope.parentModule = parentModule = parent || module.parent.parent;
mockScope.parentModule = parentModule = parent || (0, _module.getModuleParent)((0, _module.getModuleParent)(module));
};

@@ -120,3 +116,3 @@

scope();
_module2.default._load = _executor2.default;
_module2.default.overloadRequire();
(0, _wipeCache2.default)();

@@ -132,3 +128,3 @@ (0, _plugins.onEnable)((0, _mocks.getAllMocks)());

scope();
_module2.default._load = _executor.originalLoader;
_module2.default.restoreRequire();
(0, _plugins.onDisable)((0, _mocks.getAllMocks)());

@@ -141,2 +137,46 @@ mockModule.withoutIsolation();

/**
* Requires file with hooks
* @param {String|Function} file
* @param {Object|Function} overrides
*/
mockModule.proxy = function (file) {
var overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var result = 0;
var stubs = typeof overrides === 'function' ? overrides(_mock2.default.inlineConstructor) : overrides;
mockModule.inScope(function () {
Object.keys(stubs).forEach(function (key) {
return mockModule(key).from(stubs[key]);
});
mockModule.enable();
if (typeof file === 'string') {
result = _module2.default.require(_module2.default.relativeFileName(file, parentModule));
} else {
result = file();
}
mockModule.disable();
});
return result;
};
/**
* Imports file with hooks
* @param {Function} importFunction (use import)
* @param {Object|Function} overrides
*/
mockModule.module = function (importFunction) {
var overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var stubs = typeof overrides === 'function' ? overrides(_mock2.default.inlineConstructor) : overrides;
return mockModule.around(importFunction, function () {
return Object.keys(stubs).forEach(function (key) {
return mockModule(key).from(stubs[key]);
});
});
};
/**
* Creates temporary executing scope. All mocks and plugins you will add in callback will be removed at exit.

@@ -143,0 +183,0 @@ * @param callback

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});

@@ -10,2 +10,6 @@ exports.resetMock = exports.getAllMocks = exports.getMock = undefined;

var _pathParse = require('path-parse');
var _pathParse2 = _interopRequireDefault(_pathParse);
var _globals = require('./globals');

@@ -20,49 +24,50 @@

var genMock = function genMock(name) {
return {
name: name,
value: {}
};
return {
name: name,
value: {}
};
};
var resetMock = function resetMock(name) {
return (0, _globals2.default)().mocks[name] = genMock(name);
return (0, _globals2.default)().mocks[name] = genMock(name);
};
var pickFrom = function pickFrom(mocks, name) {
var ext = _common.extensions.find(function (ext) {
return mocks[name + ext];
});
if (ext !== undefined) {
return mocks[name + ext];
}
var ext = _common.extensions.find(function (ext) {
return mocks[name + ext];
});
if (ext !== undefined) {
return mocks[name + ext];
}
};
var getMock = function getMock(name) {
var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, _globals2.default)();
var mocks = scope.mocks;
var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, _globals2.default)();
var mocks = scope.mocks;
var fn = (0, _path.parse)(name);
var shortName = (0, _path.join)(fn.dir, fn.name);
var fn = (0, _pathParse2.default)(name);
var shortName = (0, _path.join)(fn.dir, fn.name);
var wshortName = fn.dir + '/' + fn.name;
var mock = pickFrom(mocks, name) || pickFrom(mocks, shortName);
var mock = pickFrom(mocks, name) || pickFrom(mocks, shortName) || pickFrom(mocks, wshortName);
if (!mock && scope.parentScope) {
return getMock(name, scope.parentScope);
}
return mock;
if (!mock && scope.parentScope) {
return getMock(name, scope.parentScope);
}
return mock;
};
var getAllMocks = function getAllMocks() {
var result = {};
var collect = function collect(scope) {
if (scope.parentScope) {
collect(scope.parentScope);
}
var mocks = scope.mocks;
Object.keys(scope.mocks).forEach(function (key) {
return result[key] = mocks[key];
});
};
collect((0, _globals2.default)());
return result;
var result = {};
var collect = function collect(scope) {
if (scope.parentScope) {
collect(scope.parentScope);
}
var mocks = scope.mocks;
Object.keys(scope.mocks).forEach(function (key) {
return result[key] = mocks[key];
});
};
collect((0, _globals2.default)());
return result;
};

@@ -69,0 +74,0 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});

@@ -19,86 +19,92 @@ exports._clearPlugins = exports.removePlugin = exports.addPlugin = exports.onEnable = exports.onDisable = exports.onMockCreate = exports.shouldMock = exports.shouldWipe = exports.convertName = undefined;

var plugins = function plugins() {
var result = [];
var collect = function collect(scope) {
result.push.apply(result, _toConsumableArray(scope.plugins));
if (scope.parentScope) {
collect(scope.parentScope);
}
};
collect((0, _globals2.default)());
//console.log('with pug',result);
return result;
var result = [];
var collect = function collect(scope) {
result.push.apply(result, _toConsumableArray(scope.plugins));
if (scope.parentScope) {
collect(scope.parentScope);
}
};
collect((0, _globals2.default)());
return result;
};
var convertName = function convertName(fileName, parentModule) {
return plugins().reduce(function (name, plugin) {
if (plugin.fileNameTransformer) {
return plugin.fileNameTransformer(name, parentModule) || name;
}
return name;
}, fileName);
var resultName = plugins().reduce(function (name, plugin) {
if (plugin.fileNameTransformer) {
return plugin.fileNameTransformer(name, parentModule) || name;
}
return name;
}, fileName);
if (typeof __webpack_modules__ !== 'undefined') {
if (resultName[0] !== '.') {
return '.' + resultName;
}
}
return resultName;
};
var triResult = function triResult(values, defaultValue) {
if (values.indexOf(_common.NO) >= 0) {
return false;
}
if (values.indexOf(_common.YES) >= 0) {
return true;
}
return defaultValue;
if (values.indexOf(_common.NO) >= 0) {
return false;
}
if (values.indexOf(_common.YES) >= 0) {
return true;
}
return defaultValue;
};
var shouldMock = function shouldMock(mock, request, parent, topModule) {
return mock.disabled ? false : triResult(plugins().map(function (plugin) {
return plugin.shouldMock ? plugin.shouldMock(mock, request, parent, topModule) : _common.PASS;
}), true);
return mock.disabled ? false : triResult(plugins().map(function (plugin) {
return plugin.shouldMock ? plugin.shouldMock(mock, request, parent, topModule) : _common.PASS;
}), true);
};
var shouldWipe = function shouldWipe(stubs, moduleName) {
return triResult(plugins().map(function (plugin) {
return plugin.wipeCheck ? plugin.wipeCheck(stubs, moduleName) : _common.PASS;
}), false);
return triResult(plugins().map(function (plugin) {
return plugin.wipeCheck ? plugin.wipeCheck(stubs, moduleName) : _common.PASS;
}), false);
};
var onMockCreate = function onMockCreate(mock) {
return plugins().reduce(function (mock, plugin) {
if (plugin.onMockCreate) {
return plugin.onMockCreate(mock) || mock;
}
return mock;
}, mock);
return plugins().reduce(function (mock, plugin) {
if (plugin.onMockCreate) {
return plugin.onMockCreate(mock) || mock;
}
return mock;
}, mock);
};
var onDisable = function onDisable(mocks) {
var plugs = plugins();
Object.keys(mocks).forEach(function (mockName) {
var mock = mocks[mockName];
plugs.forEach(function (plugin) {
return plugin.onDisable && plugin.onDisable(mock._parent);
});
var plugs = plugins();
Object.keys(mocks).forEach(function (mockName) {
var mock = mocks[mockName];
plugs.forEach(function (plugin) {
return plugin.onDisable && plugin.onDisable(mock._parent);
});
});
};
var onEnable = function onEnable(mocks) {
var plugs = plugins();
Object.keys(mocks).forEach(function (mockName) {
var mock = mocks[mockName];
plugs.forEach(function (plugin) {
return plugin.onEnable && plugin.onEnable(mock._parent);
});
var plugs = plugins();
Object.keys(mocks).forEach(function (mockName) {
var mock = mocks[mockName];
plugs.forEach(function (plugin) {
return plugin.onEnable && plugin.onEnable(mock._parent);
});
});
};
var addPlugin = function addPlugin(plugin) {
(0, _globals2.default)().plugins.push(plugin);
(0, _globals2.default)().plugins.push(plugin);
};
var removePlugin = function removePlugin(plugin) {
(0, _globals2.default)().plugins = (0, _globals2.default)().plugins.filter(function (plug) {
return plug !== plugin;
});
(0, _globals2.default)().plugins = (0, _globals2.default)().plugins.filter(function (plug) {
return plug !== plugin;
});
};
var _clearPlugins = function _clearPlugins() {
(0, _globals2.default)().plugins = [];
(0, _globals2.default)().plugins = [];
};

@@ -105,0 +111,0 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});

@@ -11,14 +11,16 @@

var _module = require('../module');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var shouldMock = function shouldMock(mock, request, parent, topModule) {
return parent.parent === topModule ? _common.PASS : _common.NO;
return (0, _module.inParents)(parent, topModule) ? _common.PASS : _common.NO;
};
var plugin = (0, _common2.default)({
shouldMock: shouldMock,
shouldMock: shouldMock,
name: 'childOnly'
name: 'childOnly'
});
exports.default = plugin;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.processFile = exports.readAlises = undefined;
exports.processFile = exports.readAliases = undefined;
var _path = require('path');
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _lodash = require('lodash.template');

@@ -22,2 +18,4 @@

var _executor = require('../../executor');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -31,183 +29,195 @@

function fileExists(path) {
try {
return !_fs2.default.accessSync(path, _fs2.default.F_OK);
} catch (e) {
return false;
}
if (typeof __webpack_modules__ !== 'undefined') {
return __webpack_modules__['.' + path] && '.' + path;
}
try {
var fs = require('fs');
return !fs.accessSync(path, fs.F_OK) && path;
} catch (e) {
return false;
}
}
function getConfigPath(configPaths) {
var conf = null;
var conf = null;
// Try all config paths and return for the first found one
(0, _lodash4.default)(configPaths, function (configPath) {
if (!configPath) return;
// Try all config paths and return for the first found one
(0, _lodash4.default)(configPaths, function (configPath) {
if (!configPath) return;
// Compile config using environment variables
var compiledConfigPath = (0, _lodash2.default)(configPath)(process.env);
// Compile config using environment variables
var compiledConfigPath = (0, _lodash2.default)(configPath)(process.env);
var resolvedConfigPath = (0, _path.resolve)(process.cwd(), compiledConfigPath);
var resolvedConfigPath = (0, _path.resolve)(process.cwd(), compiledConfigPath);
var resolvedName = fileExists(resolvedConfigPath);
if (resolvedConfigPath && fileExists(resolvedConfigPath)) {
conf = resolvedConfigPath;
}
if (resolvedConfigPath && resolvedName) {
conf = resolvedName;
}
return conf;
});
return conf;
});
return conf;
return conf;
}
function readAlises(configPath) {
var configPaths = configPath ? [configPath].concat(DEFAULT_CONFIG_NAMES) : DEFAULT_CONFIG_NAMES;
function readAliases(configPath) {
var configPaths = configPath ? [configPath].concat(DEFAULT_CONFIG_NAMES) : DEFAULT_CONFIG_NAMES;
// Get webpack config
var confPath = getConfigPath(configPaths);
// Get webpack config
var confPath = getConfigPath(configPaths);
// If the config comes back as null, we didn't find it, so throw an exception.
if (!confPath) {
throw new Error('Cannot find any of these configuration files: ' + configPaths.join(', '));
}
// If the config comes back as null, we didn't find it, so throw an exception.
if (!confPath) {
throw new Error('Cannot find any of these configuration files: ' + configPaths.join(', '));
}
// Require the config
var conf = require(confPath);
// Require the config
var conf = (0, _executor.requireModule)(confPath);
if (conf && conf.__esModule && conf.default) {
conf = conf.default;
}
if (conf && conf.__esModule && conf.default) {
conf = conf.default;
}
// exit if there's no alias config and the config is not an array
if (!(conf.resolve && conf.resolve.alias) && !Array.isArray(conf)) {
throw new Error('The resolved config file doesn\'t contain a resolve configuration');
}
// exit if there's no alias config and the config is not an array
if (!(conf.resolve && conf.resolve.alias) && !Array.isArray(conf)) {
throw new Error('The resolved config file doesn\'t contain a resolve configuration');
}
// Get the webpack alias config
var aliasConf = void 0;
var extensionsConf = void 0;
// Get the webpack alias config
var aliasConf = void 0;
var extensionsConf = void 0;
if (Array.isArray(conf)) {
// the exported webpack config is an array ...
// (i.e., the project is using webpack's multicompile feature) ...
if (Array.isArray(conf)) {
// the exported webpack config is an array ...
// (i.e., the project is using webpack's multicompile feature) ...
// reduce the configs to a single alias object
aliasConf = conf.reduce(function (prev, curr) {
var next = Object.assign({}, prev);
if (curr.resolve && curr.resolve.alias) {
Object.assign(next, curr.resolve.alias);
}
return next;
}, {});
// reduce the configs to a single alias object
aliasConf = conf.reduce(function (prev, curr) {
var next = Object.assign({}, prev);
if (curr.resolve && curr.resolve.alias) {
Object.assign(next, curr.resolve.alias);
}
return next;
}, {});
// if the object is empty, bail
if (!Object.keys(aliasConf).length) {
return;
}
// if the object is empty, bail
if (!Object.keys(aliasConf).length) {
return;
}
// reduce the configs to a single extensions array
extensionsConf = conf.reduce(function (prev, curr) {
var next = [].concat(prev);
if (curr.resolve && curr.resolve.extensions && curr.resolve.extensions.length) {
curr.resolve.extensions.forEach(function (ext) {
if (next.indexOf(ext) === -1) {
next.push(ext);
}
});
}
return next;
}, []);
// reduce the configs to a single extensions array
extensionsConf = conf.reduce(function (prev, curr) {
var next = [].concat(prev);
if (curr.resolve && curr.resolve.extensions && curr.resolve.extensions.length) {
curr.resolve.extensions.forEach(function (ext) {
if (next.indexOf(ext) === -1) {
next.push(ext);
}
});
}
return next;
}, []);
if (!extensionsConf.length) {
extensionsConf = null;
}
} else {
// the exported webpack config is a single object...
if (!extensionsConf.length) {
extensionsConf = null;
}
} else {
// the exported webpack config is a single object...
// use it's resolve.alias property
aliasConf = conf.resolve.alias;
// use it's resolve.alias property
aliasConf = conf.resolve.alias;
// use it's resolve.extensions property, if available
extensionsConf = conf.resolve.extensions && conf.resolve.extensions.length ? conf.resolve.extensions : null;
// use it's resolve.extensions property, if available
extensionsConf = conf.resolve.extensions && conf.resolve.extensions.length ? conf.resolve.extensions : null;
}
if (typeof __webpack_modules__ !== 'undefined') Object.keys(aliasConf).forEach(function (alias) {
var location = aliasConf[alias];
if (!__webpack_modules__[location]) {
aliasConf[alias] = '.' + (0, _path.resolve)((0, _path.dirname)(confPath), '.' + location);
}
});
return {
aliasConf: aliasConf,
extensionsConf: extensionsConf
};
return {
aliasConf: aliasConf,
extensionsConf: extensionsConf
};
}
function processFile(filePath, _ref) {
var aliasConf = _ref.aliasConf,
extensionsConf = _ref.extensionsConf;
var aliasConf = _ref.aliasConf,
extensionsConf = _ref.extensionsConf;
for (var aliasFrom in aliasConf) {
if (aliasConf.hasOwnProperty(aliasFrom)) {
for (var aliasFrom in aliasConf) {
if (aliasConf.hasOwnProperty(aliasFrom)) {
var aliasTo = aliasConf[aliasFrom];
var regex = new RegExp('^' + aliasFrom + '(/|$)');
var aliasTo = aliasConf[aliasFrom];
var regex = new RegExp('^' + aliasFrom + '(/|$)');
// If the regex matches, replace by the right config
if (regex.test(filePath)) {
// If the regex matches, replace by the right config
if (regex.test(filePath)) {
// notModuleRegExp from https://github.com/webpack/enhanced-resolve/blob/master/lib/Resolver.js
var notModuleRegExp = /^\.$|^\.[\\\/]|^\.\.$|^\.\.[\/\\]|^\/|^[A-Z]:[\\\/]/i;
var isModule = !notModuleRegExp.test(aliasTo);
// notModuleRegExp from https://github.com/webpack/enhanced-resolve/blob/master/lib/Resolver.js
var notModuleRegExp = /^\.$|^\.[\\\/]|^\.\.$|^\.\.[\/\\]|^\/|^[A-Z]:[\\\/]/i;
var isModule = !notModuleRegExp.test(aliasTo);
if (isModule) {
return aliasTo;
}
if (isModule) {
return aliasTo;
}
// If the filepath is not absolute, make it absolute
if (!(0, _path.isAbsolute)(aliasTo)) {
aliasTo = (0, _path.join)(process.cwd(), aliasTo);
}
var relativeFilePath = (0, _path.resolve)((0, _path.dirname)(filePath), aliasTo).split(_path.sep).join('/');
// If the filepath is not absolute, make it absolute
if (!(0, _path.isAbsolute)(aliasTo)) {
aliasTo = (0, _path.join)(process.cwd(), aliasTo);
}
var relativeFilePath = (0, _path.resolve)((0, _path.dirname)(filePath), aliasTo).split(_path.sep).join('/');
// In case the file path is the root of the alias, need to put a dot to avoid having an absolute path
if (relativeFilePath.length === 0) {
relativeFilePath = '.';
}
// In case the file path is the root of the alias, need to put a dot to avoid having an absolute path
if (relativeFilePath.length === 0) {
relativeFilePath = '.';
}
var requiredFilePath = filePath.replace(aliasFrom, relativeFilePath);
var requiredFilePath = filePath.replace(aliasFrom, relativeFilePath);
// In the unfortunate case of a file requiring the current directory which is the alias, we need to add
// an extra slash
if (requiredFilePath === '.') {
requiredFilePath = './';
}
// In the unfortunate case of a file requiring the current directory which is the alias, we need to add
// an extra slash
if (requiredFilePath === '.') {
requiredFilePath = './';
}
// In the case of a file requiring a child directory of the current directory, we need to add a dot slash
if (['.', '/'].indexOf(requiredFilePath[0]) === -1) {
requiredFilePath = './' + requiredFilePath;
}
// In the case of a file requiring a child directory of the current directory, we need to add a dot slash
if (['.', '/'].indexOf(requiredFilePath[0]) === -1) {
requiredFilePath = './' + requiredFilePath;
}
// In case the extension option is passed
if (extensionsConf) {
(function () {
// Get an absolute path to the file
var absoluteRequire = (0, _path.join)(aliasTo, (0, _path.basename)(filePath));
// In case the extension option is passed
if (extensionsConf) {
(function () {
// Get an absolute path to the file
var absoluteRequire = (0, _path.join)(aliasTo, (0, _path.basename)(filePath));
var extension = null;
(0, _lodash4.default)(extensionsConf, function (ext) {
if (!ext) return;
var extension = null;
(0, _lodash4.default)(extensionsConf, function (ext) {
if (!ext) return;
// If the file with this extension exists set it
if (fileExists(absoluteRequire + ext)) {
extension = ext;
}
// If the file with this extension exists set it
if (fileExists(absoluteRequire + ext)) {
extension = ext;
}
return extension;
});
return extension;
});
// Set the extension to the file path, or keep the original one
requiredFilePath += extension || '';
})();
}
// Set the extension to the file path, or keep the original one
requiredFilePath += extension || '';
})();
}
return requiredFilePath;
}
}
return requiredFilePath;
}
}
}
}
exports.readAlises = readAlises;
exports.readAliases = readAliases;
exports.processFile = processFile;

@@ -15,2 +15,4 @@ 'use strict';

var _module = require('../module');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -20,3 +22,3 @@

if (mock.flag_directChildOnly) {
return parent.parent === topModule ? _common.PASS : _common.NO;
return (0, _module.inParents)(parent, topModule) ? _common.PASS : _common.NO;
}

@@ -27,3 +29,3 @@ if (mock.flag_toBeCalledFromMock) {

return parent.filename in mockedModules ? _common.PASS : _common.NO;
return (0, _module.getModuleName)(parent) in mockedModules ? _common.PASS : _common.NO;
}

@@ -30,0 +32,0 @@ };

@@ -7,3 +7,3 @@ 'use strict';

var _module = require('module');
var _module = require('../module');

@@ -10,0 +10,0 @@ var _module2 = _interopRequireDefault(_module);

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});

@@ -11,35 +11,37 @@

var _module = require('../module');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var trimKey = function trimKey(key) {
return key[0] == '.' ? trimKey(key.substr(1)) : key;
return key[0] == '.' ? trimKey(key.substr(1)) : key;
};
var relativeWipeCheck = function relativeWipeCheck(stubs, moduleName) {
if (Object.keys(stubs).find(function (key) {
return moduleName.indexOf(trimKey(key)) >= 0;
})) {
return _common.YES;
}
if (Object.keys(stubs).find(function (key) {
return moduleName.indexOf(trimKey(key)) >= 0;
})) {
return _common.YES;
}
};
var fileNameTransformer = function fileNameTransformer(fileName /*, module*/) {
return fileName;
return fileName;
};
var wipeCheck = function wipeCheck(stubs, moduleName) {
return relativeWipeCheck(stubs, moduleName);
return relativeWipeCheck(stubs, moduleName);
};
var shouldMock = function shouldMock(mock, request, parent, topModule) {
return parent.parent === topModule ? _common.PASS : _common.NO;
return (0, _module.inParents)(parent, topModule) ? _common.PASS : _common.NO;
};
var plugin = (0, _common2.default)({
fileNameTransformer: fileNameTransformer,
wipeCheck: wipeCheck,
shouldMock: shouldMock,
fileNameTransformer: fileNameTransformer,
wipeCheck: wipeCheck,
shouldMock: shouldMock,
name: 'relative'
name: 'relative'
});
exports.default = plugin;

@@ -19,3 +19,3 @@ 'use strict';

var configure = function configure(fileName) {
settings = (0, _aliases.readAlises)(fileName);
settings = (0, _aliases.readAliases)(fileName);
};

@@ -22,0 +22,0 @@

'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.wipe = undefined;
var _wipeNodeCache = require('wipe-node-cache');
var _wipeNodeCache2 = _interopRequireDefault(_wipeNodeCache);
var _mocks = require('./mocks');

@@ -15,23 +12,24 @@

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// which one?
var wipe = exports.wipe = module.hot ? require('wipe-webpack-cache') : require('wipe-node-cache');
var primaryResolver = function primaryResolver(stubs, moduleName) {
return stubs[moduleName];
return stubs[moduleName];
};
var resolver = function resolver(stubs, moduleName) {
// never wipe .node(native) module
if (moduleName.indexOf('\.node') > -1) {
return false;
}
return (0, _plugins.shouldWipe)(stubs, moduleName);
// never wipe .node(native) module
if (moduleName.indexOf('\.node') > -1) {
return false;
}
return (0, _plugins.shouldWipe)(stubs, moduleName);
};
var wipeCache = function wipeCache() {
var primaryCache = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var primaryCache = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
(0, _wipeNodeCache2.default)(primaryCache, primaryResolver);
(0, _wipeNodeCache2.default)((0, _mocks.getAllMocks)(), resolver);
wipe(primaryCache, primaryResolver);
wipe((0, _mocks.getAllMocks)(), resolver);
};
exports.default = wipeCache;
{
"name": "rewiremock",
"version": "2.0.0",
"version": "2.1.0",
"description": "Easy and es6 compatible dependency mocking tool.",

@@ -11,2 +11,4 @@ "main": "lib/index.js",

"test:pick": "BABEL_ENV=test mocha --compilers js:babel-core/register",
"test:karma": "node ./node_modules/karma/bin/karma --single-run --browsers PhantomJS",
"test:browser": "node ./node_modules/karma/bin/karma start --browsers Chrome",
"build": "babel src -d lib",

@@ -17,2 +19,6 @@ "prepublish": "npm run build",

},
"files": [
"lib",
"webpack"
],
"keywords": [

@@ -35,5 +41,7 @@ "es6",

"dependencies": {
"lodash.some": "^4.6.0",
"lodash.template": "^4.4.0",
"path-parse": "false1.0.5",
"wipe-node-cache": "^1.0.2",
"lodash.some": "^4.6.0",
"lodash.template": "^4.4.0"
"wipe-webpack-cache": "^1.0.0"
},

@@ -52,4 +60,14 @@ "devDependencies": {

"eslint-plugin-mocha": "^4.9.0",
"mocha": "^3.0.2"
"karma": "^1.7.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.4",
"karma-spec-reporter": "0.0.26",
"karma-webpack": "^2.0.4",
"mocha": "^3.0.2",
"phantomjs-polyfill": "0.0.2",
"phantomjs-polyfill-object-assign": "0.0.2",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
}
}

@@ -33,3 +33,2 @@ # rewiremock [![Build Status](https://secure.travis-ci.org/theKashey/rewiremock.svg)](http://travis-ci.org/theKashey/rewiremock)

# API
see d.ts file, or JSDoc in javascript sources.

@@ -41,2 +40,4 @@ ## main API

- rewiremock.around(loader, creator) - loads a module in an asynchronous sandbox.
- rewiremock.proxy(file, stubs) - _proxyquire_ like mocking api
- rewiremock.from(loader, stubs) - _proxyquire_ like mocking api
## mocking API

@@ -57,10 +58,60 @@ - rewiremock(moduleName: string) - set name of overloading module

# Not working?
If something is not working - just check that you:
- added a plugin to transform names (nodejs, webpackAlias or relative)
- use .toBeUsed for each mocks
And they actually were mocked. If not - rewiremock will throw an Error.
# Which one?
Yep - there is 4 top level ways to activate a mock - inScope, around, proxy or just enable.
Which one to choose? Any! It just depends:
- If everything is simply - use __proxy__.
- If you need scope isolation - use __around__. inScope is just creating a scope and can be used in all cases.
- If you need full control - dont use proxy.
- As long all internal API will call __.enable/.disable__ - I would not recommend using them directly.
#Usage
```js
// proxy will load a file by it's own ( name resolution is a hard thing)
const mock = rewiremock.proxy('somemodule', (r) => ({
'dep1': { name: 'override' },
'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly() // use all `mocking API`
}));
// you can require a file by yourself. ( yep, proxy is a god function)
const mock = rewiremock.proxy(() => require('somemodule'), {
'dep1': { name: 'override' },
'dep2': { onlyDump: 'stubs' }
}));
// or use es6 import (not for node.js mjs `real` es6 modules)
const mock = await rewiremock.module(() => import('somemodule'), {
'dep1': { name: 'override' },
'dep2': { onlyDump: 'stubs' }
}));
```
# Setup
## To run with node.js
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.
## To run inside webpack enviroment.
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.
1. webpack.NamedModulesPlugin(). To enlight the real names of modules. Not "numbers".
2. webpack.HotModuleReplacementPlugin(). To provide some information about connections between modules.
3. rewiremock.webpackPlugin. To add some magic and make gears rolling.
```js
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.
## To actually... mock
First - define your mocks. You can do it in any place, this is just a setup.

@@ -119,3 +170,3 @@ ```javascript

As result - it will run faster.
# inScope

@@ -173,4 +224,21 @@ Sometimes you will have independent tests in a single file, and you might need separate mocks for each one.

```
Currently .inScope is the only API capable to handle es6 dynamic imports.
Currently .inScope is the only API capable to handle es6(not node [m]js!) dynamic imports.
# Proxy
Sometimes it is much easier to combine all the things together.
```js
// 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' }
}));
```
# Plugins

@@ -308,3 +376,9 @@ By default - rewiremock has limited features. You can extend its behavior via plugins.

```
# Not working?
If something is not working - just check that you:
- added a plugin to transform names (nodejs, webpackAlias or relative)
- use .toBeUsed for each mocks
And they actually were mocked. If not - rewiremock will throw an Error.
# Wanna read something about?

@@ -311,0 +385,0 @@ [Rewiremock - medium article](https://medium.com/@antonkorzunov/how-to-mock-dependency-in-a-node-js-and-why-2ad4386f6587)

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc