{"id":13527147,"url":"https://github.com/jhnns/rewire","last_synced_at":"2025-05-13T15:11:30.407Z","repository":{"id":3483794,"uuid":"4539386","full_name":"jhnns/rewire","owner":"jhnns","description":"Easy monkey-patching for node.js unit tests","archived":false,"fork":false,"pushed_at":"2024-04-18T22:01:33.000Z","size":608,"stargazers_count":3077,"open_issues_count":52,"forks_count":127,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-05-09T05:41:38.826Z","etag":null,"topics":["mock","monkey-patching","testing","unit-testing"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"shobhitmittal/python-pentest-tools","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jhnns.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,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-06-03T18:09:10.000Z","updated_at":"2025-04-09T14:24:50.000Z","dependencies_parsed_at":"2022-08-10T07:48:56.700Z","dependency_job_id":"69f9ee83-b0a0-4a70-bd11-9986a0b5450c","html_url":"https://github.com/jhnns/rewire","commit_stats":{"total_commits":278,"total_committers":27,"mean_commits":"10.296296296296296","dds":0.5683453237410072,"last_synced_commit":"e0ea17d2e13ef4fb054980c1c5c62edcfd10632f"},"previous_names":[],"tags_count":41,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jhnns%2Frewire","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jhnns%2Frewire/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jhnns%2Frewire/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jhnns%2Frewire/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jhnns","download_url":"https://codeload.github.com/jhnns/rewire/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253969260,"owners_count":21992263,"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":["mock","monkey-patching","testing","unit-testing"],"created_at":"2024-08-01T06:01:42.064Z","updated_at":"2025-05-13T15:11:25.390Z","avatar_url":"https://github.com/jhnns.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","testing"],"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[![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\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjhnns%2Frewire","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjhnns%2Frewire","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjhnns%2Frewire/lists"}