{"id":13473826,"url":"https://github.com/theKashey/rewiremock","last_synced_at":"2025-03-26T19:34:48.774Z","repository":{"id":46655593,"uuid":"92782642","full_name":"theKashey/rewiremock","owner":"theKashey","description":"The right way to mock dependencies in Node.js or webpack environment.","archived":false,"fork":false,"pushed_at":"2023-02-16T22:37:46.000Z","size":2684,"stargazers_count":492,"open_issues_count":37,"forks_count":30,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-10-30T06:33:34.856Z","etag":null,"topics":["dependency-injection","magic","mock","mock-library","mockery","nodejs","proxyquire","webpack"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/theKashey.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-05-29T23:26:28.000Z","updated_at":"2024-10-30T03:58:06.000Z","dependencies_parsed_at":"2024-01-13T10:42:04.611Z","dependency_job_id":"900a53e6-c3b0-42d7-9dc2-be705631c933","html_url":"https://github.com/theKashey/rewiremock","commit_stats":{"total_commits":229,"total_committers":20,"mean_commits":11.45,"dds":"0.42358078602620086","last_synced_commit":"9352c6fe25d4669b001ea6329587b7b870fe35ba"},"previous_names":[],"tags_count":65,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theKashey%2Frewiremock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theKashey%2Frewiremock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theKashey%2Frewiremock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theKashey%2Frewiremock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/theKashey","download_url":"https://codeload.github.com/theKashey/rewiremock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245495955,"owners_count":20624812,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency-injection","magic","mock","mock-library","mockery","nodejs","proxyquire","webpack"],"created_at":"2024-07-31T16:01:07.228Z","updated_at":"2025-03-26T19:34:46.993Z","avatar_url":"https://github.com/theKashey.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"```text\n                     /$$      /$$ /$$                     /$$      /$$                     /$$      \n                    | $$  /$ | $$|__/                    | $$$    /$$$                    | $$      \n  /$$$$$$   /$$$$$$ | $$ /$$$| $$ /$$  /$$$$$$   /$$$$$$ | $$$$  /$$$$  /$$$$$$   /$$$$$$$| $$   /$$\n /$$__  $$ /$$__  $$| $$/$$ $$ $$| $$ /$$__  $$ /$$__  $$| $$ $$/$$ $$ /$$__  $$ /$$_____/| $$  /$$/\n| $$  \\__/| $$$$$$$$| $$$$_  $$$$| $$| $$  \\__/| $$$$$$$$| $$  $$$| $$| $$  \\ $$| $$      | $$$$$$/ \n| $$      | $$_____/| $$$/ \\  $$$| $$| $$      | $$_____/| $$\\  $ | $$| $$  | $$| $$      | $$_  $$ \n| $$      |  $$$$$$$| $$/   \\  $$| $$| $$      |  $$$$$$$| $$ \\/  | $$|  $$$$$$/|  $$$$$$$| $$ \\  $$\n|__/       \\_______/|__/     \\__/|__/|__/       \\_______/|__/     |__/ \\______/  \\_______/|__/  \\__/\n```\n\n[![Build Status](https://travis-ci.org/theKashey/rewiremock.svg)](http://travis-ci.org/theKashey/rewiremock)\n[![coverage-badge](https://img.shields.io/codecov/c/github/thekashey/rewiremock.svg?style=flat-square)](https://codecov.io/github/thekashey/rewiremock)\n[![version-badge](https://img.shields.io/npm/v/rewiremock.svg?style=flat-square)](https://www.npmjs.com/package/rewiremock)\n[![Greenkeeper badge](https://badges.greenkeeper.io/theKashey/rewiremock.svg)](https://greenkeeper.io/)\n \n# Quick start\n## 1. Install\n- `yarn add --dev rewiremock` or `npm i --save-dev rewiremock`\n## 2. Setup\nI would recommend not importing `rewiremock` directly from tests, but create a `rewiremock.js` file and require it - in this way, you can _preconfigure_ rewiremock for all tests.\n### for ts/es6/esm use `import`\n```js\n// rewiremock.es6.js\nimport rewiremock from 'rewiremock';\n// settings\n// ....\nrewiremock.overrideEntryPoint(module); // this is important. This command is \"transfering\" this module parent to rewiremock\nexport { rewiremock }\n```\n### for commonjs/nodejs use `require('rewiremock/node')`\n```js\n// rewiremock.cjs.js\nconst rewiremock = require('rewiremock/node'); \n// nothng more than `plugins.node`, but it might change how filename resolution works\n/// settings\nrewiremock.overrideEntryPoint(module); // this is important\nmodule.exports = rewiremock;\n```\n### for webpack\n```js\n// rewiremock.es6.js\nimport rewiremock from 'rewiremock/webpack';\n/// settings\nrewiremock.overrideEntryPoint(module); // this is important\nexport { rewiremock }\n```\nYou will also need to add [a few plugins](https://github.com/theKashey/rewiremock#to-run-inside-webpack-enviroment) to your webpack test configuration (no need to keep them all in production).\n\u003e If you import `rewiremock` directly from your tests, you dont need `overrideEntryPoint`\n\n## 3. Use\nThere are 3 ways to mock, all with pros and cons.\n### proxyquire - like\nSimplest one. \n```js\n const file = rewiremock.proxy('file.js', {\n   'dependency':  stub\n });\n // or\n const file = rewiremock.proxy(() =\u003e require('file.js'), {\n    'dependency':  stub\n  });\n```\n💡to make it really \"proxyquire like\" - add `.relative` plugin. Which will allow mocking of direct dependencies only, like  with `proxyquire`\n```js\nimport rewiremock, { addPlugin, plugins } from 'rewiremock';\naddPlugin(plugins.relative);\n```\n### mockery - like\nMost powerfull one\n```js\n rewiremock('dependency').with(stub);\n rewiremock(() =\u003e require('dependency')).with(stub);\n rewiremock(() =\u003e import('dependency')).with(stub); // works with async API only\n rewiremock.enable(); \n const file = require('file.js');\n rewiremock.disable();\n```\n### jest - like\nShortest one\n```js\n // just place it next to `imports` and add a rewiremock/babel plugin \n rewiremock('dependency').with(stub); \n```\n💡 requires `rewiremock/babel` plugin \n## 4. Tune\nThere are plenty of plugins to make your life easier. For example - this is my favorite setup\n```js\nimport { resolve } from 'path';\nimport rewiremock, { addPlugin, overrideEntryPoint, plugins } from 'rewiremock';\nimport { configure } from 'rewiremock/lib/plugins/webpack-alias'; // actually dont use it\n\nconfigure(resolve(`${__dirname}/../../webpack.config.test.js`));\n\noverrideEntryPoint(module);\n// we need webpack aliases\naddPlugin(plugins.webpackAlias);\n// and all stub names would be a relative\naddPlugin(plugins.relative);\n// and all stubs should be used. Lets make it default!\naddPlugin(plugins.usedByDefault);\n\nexport { rewiremock };\n```\n\n## What command to use???!!!\n```js\n// use `require` instead of just the filename to maintain type information\nconst mock = rewiremock.proxy(() =\u003e require('somemodule'), r =\u003e {\n   'dep1': { name: 'override' },\n   // use all power of rewiremock to mock something as you want...\n   'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly(), // use all `mocking API`\n}));\n```\nThere are two important things here:\n- You can use `require` or `import` to specify the file to require and the file to mock. This helps to __resolve file names__ and maintain type information(if you have it). See `Guided Mocking` below.\n- You can mix simplified helpers (like `.proxy`) and the main API.\n\n### ESM modules\nIf you want to support ESM modules(powered by [@std/ESM](https://github.com/standard-things/esm/), not _native_ modules) you have to use the `import` function.\n- use `.module` - an \"async\" version of `.proxy`\n```js\nconst mock = await rewiremock.module(() =\u003e import('somemodule'), {...});\n```\n- or just use `import` - that would \n```\nrewiremock(() =\u003e require('xxx').with({});\nrewiremock('yyy').with({});\n\nconst file = await import('somemodule');\n```\n\nOk! Let's move forward!\n \n \n# API\n \n ## main API\n - `rewiremock.enable()` - wipes cache and enables interceptor.\n - `rewiremock.disable()` - wipes cache and disables interceptor.    \n - `rewiremock.around(loader, creator):Promise\u003c T \u003e` - loads a module in an **asynchronous** sandbox.\n - `rewiremock.proxy(file, stubs):T` - _proxyquire_ like mocking api, where file is file name, and stubs are an object or a function.\n - `rewiremock.module(loader, stubs):Promise\u003c T \u003e` - async version of proxy, where loader is a function.\n ## mocking API \n - `rewiremock(moduleName: string)` - fabric for a moduleNames's mock\n - `rewiremock(moduleImport: loader)` - async fabric for a module import function.\n    - `.enable/disable()` - to enable or disable mock (enabled by default).\n    - `.with(stubs: function | Object)` - overloads module with a value\n    - `.withDefault(stub: function | Object)` - overload `default` es6 export\n    - `.es6()` - marks module as ES6( __esModule )\n    - `.by(otherModule: string| function)` - overload by another module(if string provider) or by result of a function call. \n    - `.callThrough()` - first load the original module, and next extend it by provided stub.\n    - `.mockThrough([stubFactory])` - first load the original module, and then replaces all exports by stubs.\n    - `.dynamic()` - enables hot mock updates.     \n    - `.toBeUsed()` - enables usage checking.  \n    - `.directChildOnly` - will do mock only direct dependencies.\n    - `.calledFromMock` - will do mock only dependencies of mocked dependencies.    \n - `rewiremock.getMock(moduleName: string|loader)` - returns existing mock (_rewiremock(moduleName)_ will _override_)   \n ## isolation API\n - `rewiremock.isolation()` - enables isolation\n - `rewiremock.withoutIsolation()` - disables isolation\n - `rewiremock.passBy(pattern or function)` - enables some modules to pass throught isolation.\n ## sandboxing\n - `rewiremock.inScope(callback)` - place synchronous callback inside a sandbox.\n ## helper functions\n - `rewiremock.stubFactory(factory)` - define a stub factory for mockThrough command.\n\n ### Automocking\n Rewiremock supports (inspired by [Jest](https://facebook.github.io/jest/docs/en/manual-mocks.html)) auto `__mocks__`ing.\n \n Just create `__mocks__/fileName.js`, and `fileName.js` will be replaced by the mock. Please refer to Jest documentation for use cases.\n \n If you don't want a particular file to be replaced by its mock - you can disable it with:\n```js\n rewiremock('fileName.js').disable();\n```\n\n# Which API to use?\nYep - there are 4 top-level ways to activate a mock - `inScope`, `around`, `proxy` or just `enable`.\n\n### A common way to mock.\nRewiremock provides lots of APIs to help you set up mocks, and get the mocked module.  \n  - If everything is simple - use __rewiremock.proxy__. (~proxyquire)\n  - If you have issues with name resolve - use __rewiremock.module__ and resolve names by yourself.\n  - If you need scope isolation - use __rewiremock.around__, or inScope.\n  - If you need advanced syntax and type checking - use __rewiremock.around__.\n  - You always can just use __.enable/.disable__ (~ mockery).\n  \n\u003e All the mocks await you to provide \"stubs\" to override the real implementation.\n\u003e If you want just to ensure you have called endpoints – use rewiremock('someFile').mockThrough.    \n\n# Usage\n\n- `proxy` will load a file by its own ( keep in mind - name resolution is a complex thing)\n\n```js\nconst mock = rewiremock.proxy('somemodule', (r) =\u003e ({\n   'dep1': { name: 'override' },\n   'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly(), // use all `mocking API`\n   'dep3': r.mockThrough() // automatically create a test double  \n}));\n```\n- you can require a file by yourself. ( yep, proxy is a \"god\" function)\n```js\nconst mock = rewiremock.proxy(() =\u003e require('somemodule'), {\n   'dep1': { name: 'override' },\n   'dep2': { onlyDump: 'stubs' }  \n}));\n```\n- or use es6 `import` (not for Node.js mjs `real` es6 modules) \n`module` is an async version of proxy, so you can use imports\n```js\nconst mock = await rewiremock.module(() =\u003e import('somemodule'), {\n   'dep1': { name: 'override' },\n   'dep2': { onlyDump: 'stubs' }  \n}));\n```\n- `around` - another version of .module, where you can do just ~anything~.\n```js\nconst mock = await rewiremock.around(() =\u003e import('somemodule'), () =\u003e {\n   rewiremock('dep1').with('something');  \n   callMom();\n   // prepare mocking behavior\n}));\n```\n- `enable`/`disable` - Low level API\n```js  \n  rewiremock('someThing').with('someThingElse')\n  rewiremock.enable();\n  // require something\n  rewiremock.disable();\n```\n\nIn all the cases you can specify what exactly you want to mock, or just mock anything \n```js\n   addPlugin(plugins.mockThroughByDefault);  \n```\n\n# Hoisted mocking \nYou can also use a top-level mocking, the same as Jest could only provide\n```js\nimport sinon from 'sinon';\nimport rewiremock from 'rewiremock';\nimport Component1 from 'common/Component1';\nimport selectors from 'common/selectors';\n\nrewiremock('common/Component1').by('common/Component2');\nrewiremock('common/Component2/action').with({ action: () =\u003e {} });\nrewiremock('common/selectors').mockThrough(() =\u003e sinon.stub());\n\nselectors.findUser.returns(\"cat\"); // this is sinon stub.\n``` \nAs result Component1 will be replaced by Component2, action with empty function and \nall selectors by sinon stubs, with one configured.\n\nThis is only possible via babel plugin, and without it, this code will be executed without any sense, as long mocking\nwill be configured after the files required.\n\n### Limitations\n- Other babel plugins, including JSX, won't work inside webpack _hoisted_ code. But you may define\nany _specific_ code in \"functions\", and let JavaScript hoist it.\n- Most variables, that you have defined in the file, are not visible to __hoisted__ code, as long they are __not yet defined__.\nOnly functions will be hoisted.\n\n1. Add `rewiremock/babel` into the plugin section of your `.babelrc` or `babel.config.js` file\n```js\n// .babelrc\n{\n  \"presets\": [\n    //.....\n  ],\n  \"plugins\": [\n    \"rewiremock/babel\"\n  ]\n}\n```\n2. This example will be transpiled into\n```js\nimport sinon from 'sinon';\nimport rewiremock from 'rewiremock';\n\nrewiremock('common/Component1').by('common/Component2');\nrewiremock('common/Component2/action').with({ action: () =\u003e {} });\nrewiremock('common/selectors').mockThrough(() =\u003e sinon.stub());\n\nrewiremock.enabled();\n\nimport Component1 from 'common/Component1';\nimport selectors from 'common/selectors';\n\nrewiremock.disable();\n\nselectors.findUser.returns(\"cat\"); // this is sinon stub.\n``` \n\nKeep in mind - rewiremock will hoist mock definition next to rewiremock import.\n - You can __use__ anything __above__ rewiremock import\n - You can __mock__ anything __below__ rewiremock import\n \n### Changing the mocks after the mocking\nIt is possible to partially change mocking already being applied.\n```js\n rewiremock('./foo')\n  .callThrough()\n  .with({ action1: action1Stub1 })\n  .dynamic();\n\n const foo = require('./foo');\n foo.action == action1Stub1;\n \n rewiremock.getMock('./foo')\n   .with({ action1: action1Stub2 });\n \n //while will RESET the mock, and could not change existing ones.\n rewiremock('./foo')\n    .with({ action1: action1Stub2 });\n \n foo.action == action1Stub2;\n \n rewiremock('./foo')\n    .with({ });\n \n foo.action == theRealFoo;\n```   \n\n#### Changing the hoisted mocks\n```js\n import rewiremock from 'rewiremock';\n import foo from './foo';\n \n rewiremock('./foo') \n   .with({ action1: action1Stub1 })\n   .dynamic();\n\n const fooMock = rewiremock.getMock('./foo');\n \n describe(..., () =\u003e {\n   it('...', () =\u003e {\n     fooMock.with({ });\n     \n     // while may NOT found the mock\n     rewiremock.getMock('./foo').with({ });\n   });\n })\n```\n\n### Guided mocking\nYou may use `require` or `import` to let IDE help you to properly write fileName,\nand hide all filename resolution and transformation behind the scenes.\nBut there are things you have to keep in mind\n\n1. Resolution of synchronous API happens on .enable\n```js\nrewiremock(() =\u003e require('./fileToMock1')); // this mock would work\nrewiremock.enable();\nrewiremock(() =\u003e require('./fileToMock2')); //this mock WOULD NOT WORK!\n```\n2. Using async API will throw an error\n```js\nrewiremock(() =\u003e import('./fileToMock1'));  \nrewiremock.enable(); // this is an exception\n```\n3. Async API requires async API\n```js\nrewiremock.module( () =\u003e import('file')) // this is ok\nrewiremock.around(..., rw =\u003e rw.mock(() =\u003e import('file2'))) // this is ok\n```\n\n# Type safety\nRewiremock can provide type-safe mocks. To enable type-safety to follow these steps:\n1. Use TypeScript or Flow.\n2. Use dynamic import syntax.\n3. Use `rewiremock.around` or `rewiremock.module` to perform a mock.\n4. Use the async form of rewiremock mock declaration.\n\n```js\n// @flow\n\nimport rewiremock  from 'rewiremock';\n\nrewiremock.around(\n  () =\u003e import('./a.js'), \n  mock =\u003e {\n  mock(() =\u003e import('./b.js'))\n    .withDefault(() =\u003e \"4\")\n    .with({testB: () =\u003e 10})\n    .nonStrict() // turn off type system\n    .with({ absolutely: \"anything\" })\n  }\n);\n```\nIf default export is not exists on module 'b', or there is no named export testB, or types do not match - type system will throw.\n\nIf you will declare an async mock, it will not be resolved by the time of execution - Rewiremock will throw on Error.\n\nIf you have async imports inside a mocked file, follow this syntax\n```js\nrewiremock.around(\n  () =\u003e import('./a.js'), \n  mock =\u003e {\n  // just before loader function rewiremock enabled itself\n  mock(() =\u003e import('./b.js').then(mock=\u003emock)) // mocks `live` one `tick` more\n  // just after loader function resolved rewiremock disables itself\n    mock =\u003e {\n    ....\n    }\n  }\n);\n```\n\n# Type safety for JavaScript\nRewiremock can check mock against the real implementation. This does not perform `type checking`, but\ncould check exported names and exported types (function vs number, for example).\n\nRewiremock expects that mock will be __less or equal__ than the original file.\n```text\nrewiremock: mocked export \"somethingMissing\" does not exist in ./b.js\nrewiremock: exported type mismatch: ./b.js:default. Expected function, got number\n```\nTo activate exports comparison\n```js\n rewiremock('somemoduname')\n   .toMatchOrigin(); // to activate\n   \n// or\nimport rewiremock, { addPlugin, removePlugin, plugins } from 'rewiremock';\naddPlugin(plugins.alwaysMatchOrigin);   \n```\n \n# Setup\n\n## To run with Node.js\n  Just use it. You can also activate node.js, which will double-check all modules names on a real FS, but...\n  everything might work out of the box.\n  \u003e PS: Just use `usedByDefault` to ensure module names are resolved correctly.\n  \n  There is also a special entry point for node.js, with nodejs plugin activated, and rewiremock as es5 export\n   ```js\n   const rewiremock = require('rewiremock/node');\n   \n   // meanwhile\n   const rewiremock = require('rewiremock').default;\n   ```\n\n## To run inside webpack environment.\n  Rewiremock can `emulate` few webpack features(like aliases) in node.js environment, but it also can be run inside webpack.\n  \u003e Actually rewiremock is the first client-side mocking library\n  \n  But not so fast, handy. First, you have to have 3(!) Plugins enabled.\n  1. `webpack.NamedModulesPlugin()`. To enlight the real names of modules, not \"numbers\". __Enabled by default__ in webpack \"dev\" mode\n  2. `webpack.HotModuleReplacementPlugin()`. To provide some information about connections between modules. \n  Might be (and usually) __already enabled__, double activation of this plugin might break everything.\n  3. `rewiremock.webpackPlugin`. To add some magic and make gears rolling.\n  \n```js\nplugins: [\n    new webpack.NamedModulesPlugin(),\n    new webpack.HotModuleReplacementPlugin(),\n    new (require(\"rewiremock/webpack/plugin\"))()\n]\n```\n  That's all. Now all magic will happen at the client-side.\n  \u003e It is better to use .proxy/module command with direct require/import and leaves all names conversion to webpack.\n\n#### Hint\nFor better dev experience include special configuration of webpack\n```js\nimport rewiremock from 'rewiremock/webpack';\n```\n\n### webpack troubleshooting\nCurrently, there are 2 known problems, both for mocha+webpack, ie using node.js to run webpack bundle:\n- TypeError: Cannot read property 'webpackHotUpdate' of undefined\n\n  Caused by babel. Just don't use babel then running webpack bundles (ie babel-register). Use babel to create bundles.\n- TypeError: Cannot read property 'call' of undefined \n\n  Caused by webpack. Sometimes it does not include some important files.\n  To solve this problem just `import('rewiremock/webpack/interceptor')` in scaffolding.\n  The problem is simply - this file does not exist in the bundle.  \n\n   \n## To actually... mock   \n\nFirst - define your mocks. You can do it in any place, this is just a setup.\n```javascript\n import rewiremock from 'rewiremock';\n ...\n \n // totaly mock `fs` with your stub \n rewiremock('fs')\n    .with({\n        readFile: yourFunction\n    });\n  \n // replace path, by other module \n rewiremock('path')\n    .by('path-mock');\n \n // replace enzyme by preconfigured one  (from https://medium.com/airbnb-engineering/unlocking-test-performance-migrating-from-mocha-to-jest-2796c508ec50)\n  rewiremock('enzyme')\n     .by(({requireActual}) =\u003e {\n    // see rest of possible params in d.ts file\n         const enzyme = requireActual('enzyme');         \n         if (!mockSetup) {\n           const chai = requireActual('chai');\n           const chaiEnzyme = requireActual('chai-enzyme');\n           chai.use(chaiEnzyme());           \n         }\n         return enzyme;\n     });\n  \n // replace default export of ES6 module \n rewiremock('reactComponent')\n    .withDefault(MockedComponent)\n     \n // replace only part of some library and keep the rest \n rewiremock('someLibrary')\n    .callThrough() \n    .with({\n        onlyOneMethod\n    })\n    \n // secure yourself and from 'unexpected' mocks\n rewiremock('myDep')\n     .with(mockedDep) \n     .calledFromMock()\n```   \n   \n# Running\n There is a simply way to do it: Just enable it, and dont forget to disable it later.\n ```javascript\n  //in mocha tests\n  beforeEach( () =\u003e rewiremock.enable() );\n  //...\n  // here you will get some advantage in type casting and autocompleting.\n  // it will actually works...\n  const someModule = require('someModule'); \n  //...\n  afterEach( () =\u003e rewiremock.disable() );\n ```\n Once enabled, rewiremock will wipe all mocked modules from cache, and all modules which require them.\n \n Including your test.\n \n Once disabled it will restore everything. \n \n All unrelated to test dependencies will be kept. Node modules, react, common files - everything.\n \n As a result - it will run faster.\n  \n# inScope\n Sometimes you will have independent tests in a single file, and you might need separate mocks for each one.\n `inScope` execute callback inside a sandbox, and all mocks or plugins or anything else you have added will not leaks away.\n ```javascript\n  rewiremock.inScope( () =\u003e {\n    rewiremock('something').with(something);\n    rewiremock.enable();\n    // is 'something' mocked? Yes\n    ....\n    rewiremock.disable();\n    // is 'something' mocked? No\n    // is it still listed as mock? Yes\n  }); \n  // is 'something' mocked or listed? No\n ```\n\n# Around\n And there is a bit harder way to do it - scope.\n inScope will create a new internal scope, next you can add something new to it, and then it will be destroyed.\n It will also enable/disable rewiremock just in time.\n \n This helps keep tests in isolation.\n \n PS: scopes are nesting each other as javascript prototypes do.\n```javascript\nrewiremock.around(\n    () =\u003e import('somemodule'), // load a module. Using import or require.\n    // just before it you can specify mocks or anything else\n    (mock) =\u003e { \n        addPlugin(nodePlugin);\n\n        mock('./lib/a/foo').with(() =\u003e 'aa');\n        mock('./lib/a/../b/bar').with(() =\u003e 'bb');\n        mock('./lib/a/../b/baz').with(() =\u003e 'cc');\n    }\n) // at this point scope is dead\n    .then((mockedBaz) =\u003e { \n        expect(mockedBaz()).to.be.equal('aabbcc');\n    });\n```  \nor just \n```javascript\nrewiremock.around(() =\u003e import('somemodule')).then(mockedModule =\u003e doSomething)  \n```\nor\n```javascript\nrewiremock.around(\n    () =\u003e import('somemodule').then( mockedModule =\u003e doSomething),    \n    (mock) =\u003e aPromise   \n);\n\n```\nCurrently, `.inScope` is the only API capable to handle es6(not node [m]js!) dynamic imports.\n\n# Proxy\n Sometimes it is much easier to combine all the things.\n```js\n// preferred way - create stubs using a function, where R is mock creator\nrewiremock.proxy('somemodule', (r) =\u003e ({\n   'dep1': { name: 'override' },\n   'dep2': r.with({name: 'override' }).toBeUsed().directChildOnly() // same powerfull syntax\n}));\n\n// straight way - just provide stubs.\nrewiremock.proxy('somemodule', {\n   'dep1': { name: 'override' },\n   'dep2': { name: 'override' }\n }));\n```\n\n\n# Plugins\n By default - rewiremock has limited features. You can extend its behavior via plugins.\n - `relative`. A bit simplistic, proxyquire-like behavior. Will override only first level dependencies, and will wipe a lot of modules from a cache. If you need override at other place - use `.atAnyPlace` modificator.\n - `nodejs`. Common support to \"usual\" Node.js application. Will absolutize all paths. Will wipe cache very accurately. \n - `webpack-alias`. __deprecated__. Enables you to use webpack aliases as module names. Please [use node-js resolution](https://github.com/theKashey/rewiremock/issues/7#issuecomment-621666559) for this.\n - `childOnly`. Only first level dependencies will be mocked. \n - `protectNodeModules`. Ensures that any module from node_modules will not be wiped from a cache.\n - `toBeUsed`. Adds feature. The only plugin enabled by default.\n - `disabledByDefault`. All mocks will be disabled on create and at the end of each cycle.\n - `mockThroughByDefault`. All mocks mocked through.\n - `usedByDefault`. All mocks to be used by the fact (reverse isolation)  \n ```javascript\n import rewiremock, { addPlugin, removePlugin, plugins } from 'rewiremock';     \n \n addPlugin(plugins.webpackAlias);\n removePlugin(plugins.webpackAlias);\n ``` \n\n# Nested declarations\n If you import rewiremock from another place, for example, to add some defaults mocks - it will not gonna work.\n Each instance of rewiremock in independent.\n You have to pass your instance of rewiremock to build a library.\n PS: note, rewiremock did have nested API, but it was removed.\n  \n# Isolation\n Unit testing requires all dependencies to be mocked. All!\n To enable it, run\n ```javascript\n  rewiremock.isolation();\n  //or\n  rewiremock.withoutIsolation();\n ```\n Then active - rewiremock will throw error on require of any unknown module.\n \n The unknown is a module which is nor mocked, nor marked as pass-through. \n \n To make few modules to be `invisible` to rewiremock, run\n ```javascript\n rewiremock.passBy(/*pattern or function*/);\n \n rewiremock.passBy(/common/);\n rewiremock.passBy(/React/);\n rewiremock.passBy(/node_modules/);\n rewiremock.passBy((name) =\u003e name.indexOf('.node')\u003e=0 )\n ```\n \n \n # Reverse isolation\n  Sometimes you have to be sure, that you mock was called.\n  Isolation will protect you then you add new dependencies, `.toBeUsed` protect you from removal.\n \n # Jest\n Jest is a very popular testing framework, but it has one issue - is already contain mocking support.\n \n \u003e Do not use rewiremock and jest. Even if it is possible.\n \n ## Jest will not allow ANY other mocking library to coexists with Jest\n To use rewiremock with Jest add to the beginning of your file\n ```js\n // better to disable auto mock\n jest.disableAutomock();\n\n // Jest breaks the rules, and you have to restore nesting of modules.\n rewiremock.overrideEntryPoint(module);\n \n // There is no way to use overload by Jest require or requireActual.\n // use the version provided by rewiremock. \n require = rewiremock.requireActual;\n ```\n \n !!! the last line here may disable Jest sandboxing. !!! \n \n Also, it will disable Jest transformation, killing all the jest magics.\n \n To be able to continue using ES6/imports - you have to enforce Babel to be applied in the `common` way.\n ```js\n describe('block of tests', () =\u003e {\n   // require babel-register in describe or it block.\n   // NOT! On top level. Jest sandboxing and isolation are still in action,\n   // and will reset all settings to default\n   require(\"babel-register\");\n })\n```\n PS: Jest will set BABEL_ENV to `test`.\n \n It is better just to use `rewiremock.requireActual`, without overriding global require.\n  \n \n \n # Your own setup.\n  In most cases you have to:\n   - add plugin\n   - setup default passBy rules\n   - add some common mocks\n   - do something else.\n   \n   And it is not a good idea to do it in every test you have.\n   \n   It is better to have one setup file, which will do everything for you\n   * Part 1 - man in the middle\n```javascript\n  // this is your test file\n  \n  // instead of importing original file - import your own one\n  // import rewiremock from 'rewiremock';\n  import rewiremock from 'test/rewiremock';    \n```\n  \n  * Part 2 - create your own one\n    \n```javascript\n    // this tests/rewiremock.js\n    \n    import rewiremock, { addPlugin, overrideEntryPoint} from 'rewiremock';\n    // do anything you need\n    addPlugin(something);\n    rewiremock('somemodule').with(/*....*/);   \n    \n    // but don't forget to add some magic\n    overrideEntryPoint(module); // \u003c-- set yourself as top module\n    // PS: rewiremock will wipe this module from cache to keep magic alive.\n       \n    export default rewiremock;\n``` \n * Part 3 - enjoy.\n You extract some common code into a helper. And things become a lot easier.\n \n # Default configuration\n Absolutely the same - preconfiguring rewiremock one can achieve via default configuration.\n \n Just put __rewiremock.config.js__ in the root dir, next to project.json, and export a configuration function\n```js\n// rewiremock.config.js\nimport wrongrewiremock, {plugins} from 'rewiremock';\n\nexport default rewiremock =\u003e {\n  // do everything with \"right\" rewiremock\n  rewiremock.addPlugin(plugins.nodejs)\n}\n```\n   \n # Caching\n\nDefault cache policy follows these steps:\n\n1. Preparation:\n\n- all files required from the original test, while interceptor is active, will bypass cache.\n- all files you indicate as mocks will be removed from the cache.\n- all \"soiled\" files which rely on mocks - will also be removed from the cache.\n- repeat.\n\n2. Finalization\n- repeat all mocks and possible \"soiled\" by mocks files.\n- copy over the old cache.\n- or restore the old cache completely if `forceCacheClear` mode is set.\n\nThe last variant is the default for proxyquire and mockery, also it is more \"secure\" from different side effects.\nRegardless, default is the first variant - as a way faster, and secure enough.\n\nAs a result of this mocking strategy, you can mock any file at any level, while keeping other files cached.\n\n#### Hint  \nIf you __don't want__  this - just add `relative` plugin. It will allow mocking only for modules\n\n\u003e  _required from __module__ with __parent__ equals __entryPoint__._\n\n  PS: module with parent equals entryPoint - any module you require from the test (it is an entry point).\n  required from that module - the first level required. Simple.\n  \n  \n # Own plugins\nDon't forget - you can write your own plugins. \n plugin is an object with fields:\n ```javascript\n {\n // to transform name. Used by alias or node.js module\n fileNameTransformer: (fileName, parentModule) =\u003e fileName;\n // check should you wipe module or not. Never used :)\n wipeCheck: (stubs, moduleName) =\u003e boolean,\n // check is mocking allowed for a module. User in relative plugin\n shouldMock: (mock, requestFilename, parentModule, entryPoint) =\u003e boolean\n }\n ```\n \n# Extensions\nRewiremock will automatically try to resolve file\n- by specified name\n- adding .js, .jsx, .ts, .tsx, .mjs\n- you can override defaults\n```js\nimport {resolveExtensions} from 'rewiremock';\nresolveExtensions(['.wasm', '.mjs', '.js', '.json']);\n```\n`resolveExtensions` is quite similar to [webpack's resolve extensions](https://webpack.js.org/configuration/resolve/#resolve-extensions). \n \n# Not working?\n If something is not working - just check that you:\n  - added a plugin to transform names (Node.js, webpackAlias or relative)\n  - use .toBeUsed for each mocks\nAnd they were mocked. If not - rewiremock will throw an Error.\n  \n\n# Goal\n- give the ability to mock everything - CommonJS, ES6, inside Node.js or webpack.\n- give the ability to do correctly - isolation, type checking, powerful API\n- give the ability to do it easy - simple API to cover all the cases.\n\n# Other libraries\nDependency mocking, inspired by the best libraries:\n- [mockery](https://github.com/mfncooper/mockery) - `rewiremock` __is__ a better `mockery`, with the same interface.\n- [proxyquire](https://github.com/theKashey/proxyquire) - `rewiremock` __is__ a better `proxyquire`, with the same interface.\n- [mock-require](https://github.com/boblauer/mock-require) - things must not be complex, `rewiremock` __is__ not.\n- [jest.mocks](https://facebook.github.io/jest/docs/en/manual-mocks.html) - `jest` is awesome. As well as `rewiremock`.\n\nRewiremock is a better version of your favorite mocking library. It can be used with `mocha`, `ava`, `karma`, and anything that's not `jest`.\n\nBy design, rewiremock has the same behavior as Mockery. But it can behave like other libraries too, exposing handy interfaces to make mocking a joy. Supports type-safe mocking and provides TS/Flow types for itself.\n\n\n# Wanna read something about?\n [Rewiremock - medium article](https://medium.com/@antonkorzunov/how-to-mock-dependency-in-a-node-js-and-why-2ad4386f6587)\n [all by tag](https://medium.com/tag/rewiremock/latest)\n \n# Licence\n MIT\n \n \n\nHappy mocking!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FtheKashey%2Frewiremock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FtheKashey%2Frewiremock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FtheKashey%2Frewiremock/lists"}