UNPKG

rewiremock

Version:

Advanced dependency mocking device.

75 lines (59 loc) 2.29 kB
import path from 'path'; import { safelyRemoveCache, wipe } from './wipeCache'; import { _clearPlugins } from './plugins'; import plugins from './plugins/index'; import { getModuleName, getModuleParent } from './module'; import { setExtensions as resolveExtensions } from './constants'; import * as API from './mockModule'; import applyDefaultConfig from "./plugins/defaultConfig"; var moduleName = getModuleName(module); if (!moduleName) { throw new Error('Rewiremock: there is no "module name". If you are using Jest - disable automocking.'); } if (!getModuleParent(module)) { throw new Error('Rewiremock: there is no "parent module". Is there two HotModuleReplacementPlugins?'); } // delete core API.cleanup(); // delete self safelyRemoveCache(getModuleName(module)); export var cleanup = function cleanup() { var wipeAll = function wipeAll(stubs, moduleName) { return moduleName.indexOf(stubs) === 0; }; wipe(path.dirname(__filename), wipeAll); }; // overrideEntryPoint would be "poisoned" in nodejs entrypoint // store the real reference to it var overrideMockEntryPoint = API.mockModule.overrideEntryPoint; /** * override "parent" for rewiremock. Will wipe given parent from a cache * by default parent for rewiremock is rewiremock entrypoont, once wrapped - wrapper should set itself as a parent. * @param {Module} parentModule */ export var overrideEntryPoint = function overrideEntryPoint(parentModule) { safelyRemoveCache(getModuleName(parentModule)); overrideMockEntryPoint(getModuleParent(parentModule)); }; overrideEntryPoint(module); // instance must be clean API.mockModule.clear(); _clearPlugins(); var addPlugin = API.addPlugin; var removePlugin = API.removePlugin; //addPlugin(plugins.nodejs); addPlugin(plugins.toBeUsed); addPlugin(plugins.directChild); addPlugin(plugins.__mock__); if (typeof __webpack_require__ !== "undefined") { addPlugin(plugins.nodeLibBrowser); } applyDefaultConfig(API.mockModule); if (global['_REWIREMOCK_HOISTED_']) { global['_REWIREMOCK_HOISTED_'].forEach(function (cb) { cb(API.mockModule, { plugins: plugins, overrideEntryPoint: overrideEntryPoint }); }); global['_REWIREMOCK_HOISTED_'] = []; } export { addPlugin, removePlugin, plugins, resolveExtensions }; export default API.mockModule;