{"id":15178950,"url":"https://github.com/twbs/rewire","last_synced_at":"2025-10-01T20:32:05.929Z","repository":{"id":65974790,"uuid":"220947210","full_name":"twbs/rewire","owner":"twbs","description":"Easy monkey-patching for node.js unit tests","archived":true,"fork":true,"pushed_at":"2021-05-15T15:45:57.000Z","size":341,"stargazers_count":4,"open_issues_count":0,"forks_count":4,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-10-29T23:59:59.730Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"rensbaardman/rewire","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/twbs.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},"funding":{"github":"twbs","open_collective":"bootstrap"}},"created_at":"2019-11-11T09:38:27.000Z","updated_at":"2023-01-28T07:28:07.000Z","dependencies_parsed_at":"2023-02-19T18:01:18.829Z","dependency_job_id":null,"html_url":"https://github.com/twbs/rewire","commit_stats":null,"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twbs%2Frewire","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twbs%2Frewire/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twbs%2Frewire/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twbs%2Frewire/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/twbs","download_url":"https://codeload.github.com/twbs/rewire/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234707119,"owners_count":18874638,"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":[],"created_at":"2024-09-27T15:42:42.442Z","updated_at":"2025-10-01T20:32:00.623Z","avatar_url":"https://github.com/twbs.png","language":null,"funding_links":["https://github.com/sponsors/twbs","https://opencollective.com/bootstrap"],"categories":[],"sub_categories":[],"readme":"rewire\n======\n**Easy monkey-patching for node.js unit tests**\n\n[![](https://img.shields.io/npm/v/rewire.svg)](https://www.npmjs.com/package/rewire)\n[![](https://img.shields.io/npm/dm/rewire.svg)](https://www.npmjs.com/package/rewire)\n[![Dependency Status](https://david-dm.org/jhnns/rewire.svg)](https://david-dm.org/jhnns/rewire)\n[![Build Status](https://travis-ci.org/jhnns/rewire.svg?branch=master)](https://travis-ci.org/jhnns/rewire)\n[![Coverage Status](https://img.shields.io/coveralls/jhnns/rewire.svg)](https://coveralls.io/r/jhnns/rewire?branch=master)\n\nrewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may\n\n- inject mocks for other modules or globals like `process`\n- inspect private variables\n- override variables within the module.\n\n**Please note:** The current version of rewire is only compatible with CommonJS modules. See [Limitations](https://github.com/jhnns/rewire#limitations).\n\n\u003cbr\u003e\n\nInstallation\n------------\n\n`npm install rewire`\n\n\u003cbr /\u003e\n\nIntroduction\n------------\n\nImagine you want to test this module:\n\n```javascript\n// lib/myModule.js\n// With rewire you can change all these variables\nvar fs = require(\"fs\"),\n    path = \"/somewhere/on/the/disk\";\n\nfunction readSomethingFromFileSystem(cb) {\n    console.log(\"Reading from file system ...\");\n    fs.readFile(path, \"utf8\", cb);\n}\n\nexports.readSomethingFromFileSystem = readSomethingFromFileSystem;\n```\n\nNow within your test module:\n\n```javascript\n// test/myModule.test.js\nvar rewire = require(\"rewire\");\n\nvar myModule = rewire(\"../lib/myModule.js\");\n```\n\nrewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.\n\n```javascript\nmyModule.__set__(\"path\", \"/dev/null\");\nmyModule.__get__(\"path\"); // = '/dev/null'\n```\n\nThis allows you to mock everything in the top-level scope of the module, like the fs module for example. Just pass the variable name as first parameter and your mock as second.\n\n```javascript\nvar fsMock = {\n    readFile: function (path, encoding, cb) {\n        expect(path).to.equal(\"/somewhere/on/the/disk\");\n        cb(null, \"Success!\");\n    }\n};\nmyModule.__set__(\"fs\", fsMock);\n\nmyModule.readSomethingFromFileSystem(function (err, data) {\n    console.log(data); // = Success!\n});\n```\n\nYou can also set multiple variables with one call.\n\n```javascript\nmyModule.__set__({\n    fs: fsMock,\n    path: \"/dev/null\"\n});\n```\n\nYou may also override globals. These changes are only within the module, so you don't have to be concerned that other modules are influenced by your mock.\n\n```javascript\nmyModule.__set__({\n    console: {\n        log: function () { /* be quiet */ }\n    },\n    process: {\n        argv: [\"testArg1\", \"testArg2\"]\n    }\n});\n```\n\n`__set__` returns a function which reverts the changes introduced by this particular `__set__` call\n\n```javascript\nvar revert = myModule.__set__(\"port\", 3000);\n\n// port is now 3000\nrevert();\n// port is now the previous value\n```\n\nFor your convenience you can also use the `__with__` method which reverts the given changes after it finished.\n\n```javascript\nmyModule.__with__({\n    port: 3000\n})(function () {\n    // within this function port is 3000\n});\n// now port is the previous value again\n```\n\nThe `__with__` method is also aware of promises. If a thenable is returned all changes stay until the promise has either been resolved or rejected.\n\n```javascript\nmyModule.__with__({\n    port: 3000\n})(function () {\n    return new Promise(...);\n}).then(function () {\n    // now port is the previous value again\n});\n// port is still 3000 here because the promise hasn't been resolved yet\n```\n\n\u003cbr /\u003e\n\nLimitations\n-----------\n\n**Babel's ES module emulation**\u003cbr\u003e\nDuring the transpilation step from ESM to CJS modules, Babel renames internal variables. Rewire will not work in these cases (see [#62](https://github.com/jhnns/rewire/issues/62)). Other Babel transforms, however, should be fine. Another solution might be switching to [babel-plugin-rewire](https://github.com/speedskater/babel-plugin-rewire).\n\n**Variables inside functions**\u003cbr\u003e\nVariables inside functions can not be changed by rewire. This is constrained by the language.\n\n```javascript\n// myModule.js\n(function () {\n    // Can't be changed by rewire\n    var someVariable;\n})()\n```\n\n**Modules that export primitives**\u003cbr\u003e\nrewire is not able to attach the `__set__`- and `__get__`-method if your module is just exporting a primitive. Rewiring does not work in this case.\n\n```javascript\n// Will throw an error if it's loaded with rewire()\nmodule.exports = 2;\n```\n\n**Globals with invalid variable names**\u003cbr\u003e\nrewire imports global variables into the local scope by prepending a list of `var` declarations:\n\n```javascript\nvar someGlobalVar = global.someGlobalVar;\n```\n\nIf `someGlobalVar` is not a valid variable name, rewire just ignores it. **In this case you're not able to override the global variable locally**.\n\n**Special globals**\u003cbr\u003e\nPlease be aware that you can't rewire `eval()` or the global object itself.\n\n\n\u003cbr /\u003e\n\nAPI\n---\n\n### rewire(filename: String): rewiredModule\n\nReturns a rewired version of the module found at `filename`. Use `rewire()` exactly like `require()`.\n\n### rewiredModule.\u0026#95;\u0026#95;set\u0026#95;\u0026#95;(name: String, value: *): Function\n\nSets the internal variable `name` to the given `value`. Returns a function which can be called to revert the change.\n\n### rewiredModule.\u0026#95;\u0026#95;set\u0026#95;\u0026#95;(obj: Object): Function\n\nTakes all enumerable keys of `obj` as variable names and sets the values respectively. Returns a function which can be called to revert the change.\n\n### rewiredModule.\u0026#95;\u0026#95;get\u0026#95;\u0026#95;(name: String): *\n\nReturns the private variable with the given `name`.\n\n### rewiredModule.\u0026#95;\u0026#95;with\u0026#95;\u0026#95;(obj: Object): Function\u0026lt;callback: Function\u003e\n\nReturns a function which - when being called - sets `obj`, executes the given `callback` and reverts `obj`. If `callback` returns a promise, `obj` is only reverted after the promise has been resolved or rejected. For your convenience the returned function passes the received promise through.\n\n\u003cbr /\u003e\n\nCaveats\n-------\n\n**Difference to require()**\u003cbr\u003e\nEvery call of rewire() executes the module again and returns a fresh instance.\n\n```javascript\nrewire(\"./myModule.js\") === rewire(\"./myModule.js\"); // = false\n```\n\nThis can especially be a problem if the module is not idempotent [like mongoose models](https://github.com/jhnns/rewire/issues/27).\n\n**Globals are imported into the module's scope at the time of rewiring**\u003cbr\u003e\nSince rewire imports all gobals into the module's scope at the time of rewiring, property changes on the `global` object after that are not recognized anymore. This is a [problem when using sinon's fake timers *after* you've called `rewire()`](http://stackoverflow.com/questions/34885024/when-using-rewire-and-sinon-faketimer-order-matters/36025128).\n\n**Dot notation**\u003cbr\u003e\nAlthough it is possible to use dot notation when calling `__set__`, it is strongly discouraged in most cases. For instance, writing `myModule.__set__(\"console.log\", fn)` is effectively the same as just writing `console.log = fn`. It would be better to write:\n\n```javascript\nmyModule.__set__(\"console\", {\n    log: function () {}\n});\n```\n\nThis replaces `console` just inside `myModule`. That is, because rewire is using `eval()` to turn the key expression into an assignment. Hence, calling `myModule.__set__(\"console.log\", fn)` modifies the `log` function on the *global* `console` object.\n\n\u003cbr /\u003e\n\nwebpack\n-------\nSee [rewire-webpack](https://github.com/jhnns/rewire-webpack)\n\n\u003cbr /\u003e\n\nCoffeeScript\n------------\n\nGood news to all caffeine-addicts: rewire works also with [Coffee-Script](http://coffeescript.org/). Note that in this case you need to install the `coffeescript` package.\n\n\u003cbr /\u003e\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwbs%2Frewire","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftwbs%2Frewire","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwbs%2Frewire/lists"}