{"name":"rewire","version":"8.0.0","keywords":["dependency","injection","mock","shim","module","unit","test","leak","inspect","fake","require"],"author":{"name":"Johannes Ewald","email":"mail@johannesewald.de"},"license":"MIT","_id":"rewire@8.0.0","maintainers":[{"name":"jhnns","email":"mail@johannesewald.de"},{"name":"peeri","email":"shared@peerigon.com"}],"homepage":"https://github.com/jhnns/rewire","bugs":{"url":"https://github.com/jhnns/rewire/issues","email":"mail@johannesewald.de"},"dist":{"shasum":"f4538b74f54e7b045a21132663b837f30bb82ec2","tarball":"http://registry-npm.ywwl.com/rewire/download/rewire-8.0.0.tgz","fileCount":12,"integrity":"sha512-30aZREqOFlNkNFbv6aSen7TMaS+jAKh2O+EH8EB1/THhgzZ/vIwqh0cDgyud1v+fanFinxXF//Q9SJEBwc/mHg==","signatures":[{"sig":"MEUCIAwJaqjZbX5aZjSkpO9MUoArgKevlhUga+hffMDAjdtEAiEAwb5dAiJqpQ7j4Zn0lJeQ9DJvbTdKN7VgQJKdVaPPqHo=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":26154,"size":8937,"noattachment":false,"key":"/rewire/-/rewire-8.0.0.tgz"},"main":"lib/index.js","gitHead":"883ef1bdabca51cc883f8ac2eb9752ea842abd4d","scripts":{"test":"nyc --reporter=html --reporter=lcov mocha -r ts-node/register -R spec"},"_npmUser":{"name":"jhnns","email":"mail@johannesewald.de"},"repository":{"url":"git://github.com/jhnns/rewire.git","type":"git"},"_npmVersion":"10.9.2","description":"Easy dependency injection for node.js unit testing","directories":{},"_nodeVersion":"22.16.0","dependencies":{"eslint":"^8.47.0"},"_hasShrinkwrap":false,"devDependencies":{"nyc":"^17.1.0","mocha":"^11.4.0","rewire":"file://.","ts-node":"^10.9.0","expect.js":"^0.3.1","typescript":"^4.6.4","@types/node":"^22.15.21"},"_npmOperationalInternal":{"tmp":"tmp/rewire_8.0.0_1748990797040_0.9666312412986131","host":"s3://npm-registry-packages-npm-production"},"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<br>\n\nInstallation\n------------\n\n`npm install rewire`\n\n<br />\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<br />\n\nLimitations\n-----------\n\n**Babel's ES module emulation**<br>\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**<br>\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**<br>\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**<br>\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**<br>\nPlease be aware that you can't rewire `eval()` or the global object itself.\n\n\n<br />\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.&#95;&#95;set&#95;&#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.&#95;&#95;set&#95;&#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.&#95;&#95;get&#95;&#95;(name: String): *\n\nReturns the private variable with the given `name`.\n\n### rewiredModule.&#95;&#95;with&#95;&#95;(obj: Object): Function&lt;callback: Function>\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<br />\n\nCaveats\n-------\n\n**Difference to require()**<br>\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**<br>\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**<br>\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<br />\n\nwebpack\n-------\nSee [rewire-webpack](https://github.com/jhnns/rewire-webpack)\n\n<br />\n\n## License\n\nMIT\n","publish_time":1748990797260,"_cnpm_publish_time":1748990797260,"dist-tags":{"latest":"9.0.1"}}