pax_global_header00006660000000000000000000000064135242676350014527gustar00rootroot0000000000000052 comment=aaae2966fac9643225816156e25b2d5db838d108 proxyquire-2.1.3/000077500000000000000000000000001352426763500137615ustar00rootroot00000000000000proxyquire-2.1.3/.github/000077500000000000000000000000001352426763500153215ustar00rootroot00000000000000proxyquire-2.1.3/.github/FUNDING.yml000066400000000000000000000000431352426763500171330ustar00rootroot00000000000000github: thlorenz patreon: thlorenz proxyquire-2.1.3/.gitignore000066400000000000000000000002251352426763500157500ustar00rootroot00000000000000*.user.js lib-cov *.seed *.log *.csv *.dat *.out *.pid *.gz pids logs results node_modules npm-debug.log spikes *.idea *.iml .DS_Store coverage proxyquire-2.1.3/.jshintrc000066400000000000000000000001401352426763500156010ustar00rootroot00000000000000{ "laxcomma" : true , "sub" : true , "onecase" : true , "node" : true } proxyquire-2.1.3/.travis.yml000066400000000000000000000002411352426763500160670ustar00rootroot00000000000000language: node_js node_js: - '4' - '6' - '8' env: - CXX=g++-4.8 addons: apt: sources: - ubuntu-toolchain-r-test packages: - g++-4.8proxyquire-2.1.3/LICENSE000066400000000000000000000020661352426763500147720ustar00rootroot00000000000000Copyright 2013 Thorsten Lorenz. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. proxyquire-2.1.3/README.md000066400000000000000000000365741352426763500152570ustar00rootroot00000000000000# proxyquire [![Build Status](https://secure.travis-ci.org/thlorenz/proxyquire.svg?branch=master)](http://travis-ci.org/thlorenz/proxyquire) become a patron Proxies nodejs's require in order to make overriding dependencies during testing easy while staying **totally unobtrusive**. If you want to stub dependencies for your client side modules, try [proxyquireify](https://github.com/thlorenz/proxyquireify), a proxyquire for [browserify v2](https://github.com/substack/browserify) or [proxyquire-universal](https://github.com/bendrucker/proxyquire-universal) to test in both Node and the browser. # Features - **no changes to your code** are necessary - non overridden methods of a module behave like the original - mocking framework agnostic, if it can stub a function then it works with proxyquire - "use strict" compliant # Example **foo.js:** ```javascript var path = require('path'); module.exports.extnameAllCaps = function (file) { return path.extname(file).toUpperCase(); }; module.exports.basenameAllCaps = function (file) { return path.basename(file).toUpperCase(); }; ``` **foo.test.js:** ```javascript var proxyquire = require('proxyquire') , assert = require('assert') , pathStub = { }; // when no overrides are specified, path.extname behaves normally var foo = proxyquire('./foo', { 'path': pathStub }); assert.strictEqual(foo.extnameAllCaps('file.txt'), '.TXT'); // override path.extname pathStub.extname = function (file) { return 'Exterminate, exterminate the ' + file; }; // path.extname now behaves as we told it to assert.strictEqual(foo.extnameAllCaps('file.txt'), 'EXTERMINATE, EXTERMINATE THE FILE.TXT'); // path.basename and all other path module methods still function as before assert.strictEqual(foo.basenameAllCaps('/a/b/file.txt'), 'FILE.TXT'); ``` You can also replace functions directly: **get.js:** ```js var get = require('simple-get'); var assert = require('assert'); module.exports = function fetch (callback) { get('https://api/users', callback); }; ``` **get.test.js:** ```js var proxyquire = require('proxyquire').noCallThru(); var assert = require('assert'); var fetch = proxyquire('./get', { 'simple-get': function (url, callback) { process.nextTick(function () { callback(null, { statusCode: 200 }) }) } }); fetch(function (err, res) { assert(res.statusCode, 200) }); ``` **Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* - [Usage](#usage) - [API](#api) - [Preventing call thru to original dependency](#preventing-call-thru-to-original-dependency) - [Prevent call thru for all future stubs resolved by a proxyquire instance](#prevent-call-thru-for-all-future-stubs-resolved-by-a-proxyquire-instance) - [Re-enable call thru for all future stubs resolved by a proxyquire instance](#re-enable-call-thru-for-all-future-stubs-resolved-by-a-proxyquire-instance) - [All together, now](#all-together-now) - [Using proxyquire to simulate the absence of Modules](#using-proxyquire-to-simulate-the-absence-of-modules) - [Forcing proxyquire to reload modules](#forcing-proxyquire-to-reload-modules) - [Globally override require](#globally-override-require) - [Caveat](#caveat) - [Globally override require during module initialization](#globally-override-require-during-module-initialization) - [Why is proxyquire messing with my `require` cache?](#why-is-proxyquire-messing-with-my-require-cache) - [Globally override require during module runtime](#globally-override-require-during-module-runtime) - [Configuring proxyquire by setting stub properties](#configuring-proxyquire-by-setting-stub-properties) - [Backwards Compatibility for proxyquire v0.3.x](#backwards-compatibility-for-proxyquire-v03x) - [Examples](#examples) - [More Examples](#more-examples) # Usage Two simple steps to override require in your tests: - add `var proxyquire = require('proxyquire');` to top level of your test file - `proxyquire(...)` the module you want to test and pass along stubs for modules you want to override # API ***proxyquire({string} request, {Object} stubs)*** - **request**: path to the module to be tested e.g., `../lib/foo` - **stubs**: key/value pairs of the form `{ modulePath: stub, ... }` - module paths are relative to the tested module **not** the test file - therefore specify it exactly as in the require statement inside the tested file - values themselves are key/value pairs of functions/properties and the appropriate override ## Preventing call thru to original dependency By default proxyquire calls the function defined on the *original* dependency whenever it is not found on the stub. If you prefer a more strict behavior you can prevent *callThru* on a per module or contextual basis. If *callThru* is disabled, you can stub out modules that don't even exist on the machine that your tests are running on. While I wouldn't recommend this in general, I have seen cases where it is legitimately useful (e.g., when requiring global environment configs in json format that may not be available on all machines). **Prevent call thru on path stub:** ```javascript var foo = proxyquire('./foo', { path: { extname: function (file) { ... } , '@noCallThru': true } }); ``` ### Prevent call thru for all future stubs resolved by a proxyquire instance ```javascript // all stubs resolved by proxyquireStrict will not call through by default var proxyquireStrict = require('proxyquire').noCallThru(); // all stubs resolved by proxyquireNonStrict will call through by default var proxyquireNonStrict = require('proxyquire'); ``` ### Re-enable call thru for all future stubs resolved by a proxyquire instance ```javascript proxyquire.callThru(); ``` **Call thru configurations per module override `callThru()`:** Passing `@noCallThru: false` when configuring modules will override `noCallThru()`: ```javascript var foo = proxyquire .noCallThru() .load('./foo', { // no calls to original './bar' methods will be made './bar' : { toAtm: function (val) { ... } } // for 'path' module they will be made , path: { extname: function (file) { ... } , '@noCallThru': false } }); ``` #### All together, now ```javascript var proxyquire = require('proxyquire').noCallThru(); // all methods for foo's dependencies will have to be stubbed out since proxyquire will not call through var foo = proxyquire('./foo', stubs); proxyquire.callThru(); // only some methods for foo's dependencies will have to be stubbed out here since proxyquire will now call through var foo2 = proxyquire('./foo', stubs); ``` ## Using proxyquire to simulate the absence of Modules Some libraries may behave differently in the presence or absence of a package, for example: ```javascript var cluster; try { cluster = require('cluster'); } catch(e) { // cluster module is not present. cluster = null } if (cluster) { // Then provide some functionality for a cluster-aware version of Node.js } else { // and some alternative for a cluster-unaware version. } ``` To exercise the second branch of the `if` statement, you can make proxyquire pretend the package isn't present by setting the stub for it to `null`. This works even if a `cluster` module is actually present. ```javascript var foo = proxyquire('./foo', { cluster: null }); ``` ## Forcing proxyquire to reload modules In most situations it is fine to have proxyquire behave exactly like nodejs `require`, i.e. modules that are loaded once get pulled from the cache the next time. For some tests however you need to ensure that the module gets loaded fresh everytime, i.e. if that causes initializing some dependency or some module state. For this purpose proxyquire exposes the `noPreserveCache` function. ```js // ensure we don't get any module from the cache, but to load it fresh every time var proxyquire = require('proxyquire').noPreserveCache(); var foo1 = proxyquire('./foo', stubs); var foo2 = proxyquire('./foo', stubs); var foo3 = require('./foo'); // foo1, foo2 and foo3 are different instances of the same module assert.notStrictEqual(foo1, foo2); assert.notStrictEqual(foo1, foo3); ``` `proxyquire.preserveCache` allows you to restore the behavior to match nodejs's `require` again. ```js proxyquire.preserveCache(); var foo1 = proxyquire('./foo', stubs); var foo2 = proxyquire('./foo', stubs); var foo3 = require('./foo'); // foo1, foo2 and foo3 are the same instance assert.strictEqual(foo1, foo2); assert.strictEqual(foo1, foo3); ``` ## Globally override require Use the `@global` property to override every `require` of a module, even transitively. ### Caveat You should **think very hard about alternatives before using this feature**. Why, because it's intrusive and as you'll see if you read on it changes the default behavior of module initialization which means that code runs differently during testing than it does normally. Additionally it **makes it harder to reason about how your tests work**. > Yeah, we are mocking `fs` three levels down in `bar`, so that's why we have to set it up when testing `foo` **WAAAT???** If you write proper unit tests you should never have a need for this. So here are some techniques to consider: - test each module in isolation - make sure your modules are small enough and do only one thing - stub out dependencies directly instead of stubbing something inside your dependencies - if you are testing `bar` and `bar` calls `foo.read` and `foo.read` calls `fs.readFile` proceed as follows - **do not** stub out `fs.readFile` globally - instead stub out `foo` so you can control what `foo.read` returns without ever even hitting `fs` OK, made it past the warnings and still feel like you need this? Read on then but you are on your own now, this is as far as I'll go ;) Watch out for more warnings below. ### Globally override require during module initialization ```javascript // foo.js var bar = require('./bar'); module.exports = function() { bar(); } // bar.js var baz = require('./baz'); module.exports = function() { baz.method(); } // baz.js module.exports = { method: function() { console.info('hello'); } } // test.js var stubs = { './baz': { method: function(val) { console.info('goodbye'); }, '@global': true } }; var proxyquire = require('proxyquire'); var foo = proxyquire('./foo', stubs); foo(); // 'goodbye' is printed to stdout ``` Be aware that when using global overrides **any module initialization code will be re-executed for each require.** This is not normally the case since node.js caches the return value of `require`, however to make global overrides work , `proxyquire` bypasses the module cache. This may cause **unexpected behaviour if a module's initialization causes side effects**. As an example consider this module which opens a file during its initialization: ```javascript var fs = require('fs') , C = require('C'); // will get executed twice var file = fs.openSync('/tmp/foo.txt', 'w'); module.exports = function() { return new C(file); }; ``` The file at `/tmp/foo.txt` could be created and/or truncated more than once. ### Why is proxyquire messing with my `require` cache? Say you have a module, C, that you wish to stub. You require module A which contains `require('B')`. Module B in turn contains `require('C')`. If module B has already been required elsewhere then when module A receives the cached version of module B and proxyquire would have no opportunity to inject the stub for C. Therefore when using the `@global` flag, `proxyquire` will bypass the `require` cache. ### Globally override require during module runtime Say you have a module that looks like this: ```javascript module.exports = function() { var d = require('d'); d.method(); }; ``` The invocation of `require('d')` will happen at runtime and not when the containing module is requested via `require`. If you want to globally override `d` above, use the `@runtimeGlobal` property: ```javascript var stubs = { 'd': { method: function(val) { console.info('hello world'); }, '@runtimeGlobal': true } }; ``` This will cause module setup code to be re-excuted just like `@global`, but with the difference that it will happen every time the module is requested via `require` at runtime as no module will ever be cached. This can cause subtle bugs so if you can guarantee that your modules will not vary their `require` behaviour at runtime, use `@global` instead. ## Configuring proxyquire by setting stub properties Even if you want to override a module that exports a function directly, you can still set special properties like `@global`. You can use a named function or assign your stub function to a variable to add properties: ```js foo['@global'] = true; function foo () {} proxyquire('./bar', { foo: foo }); ``` And if your stub is in a separate module where `module.exports = foo`: ```js var foostub = require('../stubs/foostub'); foostub['@global'] = true; proxyquire('bar', { foo: foostub }); ``` # Backwards Compatibility for proxyquire v0.3.x Compatibility mode with proxyquire v0.3.x **has been removed**. You should update your code to use the newer API but if you can't, pin the version of proxyquire in your package.json file to ~0.6 in order to continue using the older style. # Examples **We are testing foo which depends on bar:** ```javascript // bar.js module module.exports = { toAtm: function (val) { return 0.986923267 * val; } }; // foo.js module // requires bar which we will stub out in tests var bar = require('./bar'); [ ... ] ``` **Tests:** ```javascript // foo-test.js module which is one folder below foo.js (e.g., in ./tests/) /* * Option a) Resolve and override in one step: */ var foo = proxyquire('../foo', { './bar': { toAtm: function (val) { return 0; /* wonder what happens now */ } } }); // [ .. run some tests .. ] /* * Option b) Resolve with empty stub and add overrides later */ var barStub = { }; var foo = proxyquire('../foo', { './bar': barStub }); // Add override barStub.toAtm = function (val) { return 0; /* wonder what happens now */ }; [ .. run some tests .. ] // Change override barStub.toAtm = function (val) { return -1 * val; /* or now */ }; [ .. run some tests .. ] // Resolve foo and override multiple of its dependencies in one step - oh my! var foo = proxyquire('./foo', { './bar' : { toAtm: function (val) { return 0; /* wonder what happens now */ } } , path : { extname: function (file) { return 'exterminate the name of ' + file; } } }); ``` # More Examples For more examples look inside the [examples folder](https://github.com/thlorenz/proxyquire/tree/master/examples/) or look through the [tests](https://github.com/thlorenz/proxyquire/blob/master/test/proxyquire.js) **Specific Examples:** - test async APIs synchronously: [examples/async](https://github.com/thlorenz/proxyquire/tree/master/examples/async). - using proxyquire with [Sinon.JS](http://sinonjs.org/): [examples/sinon](https://github.com/thlorenz/proxyquire/tree/master/examples/sinon). proxyquire-2.1.3/examples/000077500000000000000000000000001352426763500155775ustar00rootroot00000000000000proxyquire-2.1.3/examples/api/000077500000000000000000000000001352426763500163505ustar00rootroot00000000000000proxyquire-2.1.3/examples/api/api-test.js000066400000000000000000000062611352426763500204410ustar00rootroot00000000000000'use strict' var assert = require('assert') var stats = require('./samples/stats') var proxyquire = require('../..') var file = '/some/path/test.ext' var foo var fooCut var fooWild var cutBarStub = { bar: function () { return 'barber' } } var wildBarStub = { bar: function () { return 'barbar' } } foo = proxyquire('./samples/foo', { }) fooCut = proxyquire('./samples/foo', { './bar': cutBarStub }) fooWild = proxyquire('./samples/foo', { './bar': wildBarStub }) assert.strictEqual(stats.fooRequires(), 3) assert.strictEqual(foo.bigBar(), 'BAR') assert.strictEqual(fooCut.bigBar(), 'BARBER') assert.strictEqual(fooWild.bigBar(), 'BARBAR') // non overriden keys call thru by default assert.strictEqual(foo.bigRab(), 'RAB') assert.strictEqual(fooCut.bigRab(), 'RAB') // non overridden module path untouched assert.strictEqual(foo.bigExt(file), '.EXT') assert.strictEqual(fooCut.bigExt(file), '.EXT') assert.strictEqual(fooWild.bigExt(file), '.EXT') assert.strictEqual(foo.bigBas(file), 'TEST.EXT') assert.strictEqual(fooCut.bigBas(file), 'TEST.EXT') assert.strictEqual(fooWild.bigBas(file), 'TEST.EXT') // overriding keys after require works for both inline and non inline requires cutBarStub.bar = function () { return 'friseur' } cutBarStub.rab = function () { return 'rabarber' } assert.strictEqual(fooCut.bigBar(), 'FRISEUR') assert.strictEqual(fooCut.bigRab(), 'RABARBER') // autofilling keys on delete only works for inline requires cutBarStub.bar = undefined assert.strictEqual(fooCut.bigBar(), 'BAR') cutBarStub.rab = undefined assert.throws(fooCut.bigRab) // turn off callThru feature via noCallThru // not turned off foo = proxyquire('./samples/foo', { path: { extname: function (file) { return 'Exterminate, exterminate the ' + file } } }) assert.strictEqual(foo.bigExt(file), 'EXTERMINATE, EXTERMINATE THE /SOME/PATH/TEST.EXT') assert.strictEqual(foo.bigBas(file), 'TEST.EXT') // turned off foo = proxyquire('./samples/foo', { path: { extname: function (file) { return 'Exterminate, exterminate the ' + file }, '@noCallThru': true } }) assert.strictEqual(foo.bigExt(file), 'EXTERMINATE, EXTERMINATE THE /SOME/PATH/TEST.EXT') assert.throws(foo.bigBas) // turned off globally // not turned back on per module foo = proxyquire .noCallThru() .load('./samples/foo', { path: { extname: function (file) { return 'Exterminate, exterminate the ' + file } } }) assert.throws(foo.bigBas) // turned back on per module foo = proxyquire .noCallThru() .load('./samples/foo', { path: { extname: function (file) { return 'Exterminate, exterminate the ' + file }, '@noCallThru': false } }) assert.strictEqual(foo.bigBas(file), 'TEST.EXT') // turned back on globally foo = proxyquire .callThru() .load('./samples/foo', { path: { extname: function (file) { return 'Exterminate, exterminate the ' + file } } }) assert.strictEqual(foo.bigBas(file), 'TEST.EXT') // turned back off per module foo = proxyquire .callThru() .load('./samples/foo', { path: { extname: function (file) { return 'Exterminate, exterminate the ' + file }, '@noCallThru': true } }) assert.throws(foo.bigBas) console.log('*** All Asserts passed ***') proxyquire-2.1.3/examples/api/samples/000077500000000000000000000000001352426763500200145ustar00rootroot00000000000000proxyquire-2.1.3/examples/api/samples/bar.js000066400000000000000000000001601352426763500211130ustar00rootroot00000000000000function bar () { return 'bar' } function rab () { return 'rab' } module.exports = { bar: bar, rab: rab } proxyquire-2.1.3/examples/api/samples/foo.js000066400000000000000000000010031352426763500211270ustar00rootroot00000000000000var stats = require('./stats') var bar = require('./bar') var path = require('path') stats.incFooRequires() function bigBar () { // inline require return require('./bar').bar().toUpperCase() } function bigRab () { // module wide require return bar.rab().toUpperCase() } function bigExt (file) { return path.extname(file).toUpperCase() } function bigBas (file) { return path.basename(file).toUpperCase() } module.exports = { bigBar: bigBar, bigRab: bigRab, bigExt: bigExt, bigBas: bigBas } proxyquire-2.1.3/examples/api/samples/stats.js000066400000000000000000000002141352426763500215050ustar00rootroot00000000000000var fooRequires = 0 module.exports = { fooRequires: function () { return fooRequires }, incFooRequires: function () { fooRequires++ } } proxyquire-2.1.3/examples/async/000077500000000000000000000000001352426763500167145ustar00rootroot00000000000000proxyquire-2.1.3/examples/async/foo-tests.js000066400000000000000000000022161352426763500211760ustar00rootroot00000000000000'use strict' var path = require('path') require('../example-utils').listModuleAndTests(path.resolve(__dirname, '/foo.js'), __filename) // Overriding callbacks that would normally be async will cause them to call back immediately // Thus allowing you to run synchronous tests against async APIs. var proxyquire = require('../..') var assert = require('assert') var readdirError = new Error('some error') var fsStub = { } var calledBack var foo = proxyquire('./foo', { fs: fsStub }) /* * Test caps locking of returned files */ fsStub.readdir = function (dir, cb) { cb(null, ['file1', 'file2']) } calledBack = false foo.filesAllCaps('./somedir', function (err, files) { assert.strictEqual(err, null) assert.strictEqual(files[0], 'FILE1') assert.strictEqual(files[1], 'FILE2') calledBack = true }) // fs.readdir and thus filesAllCaps calls back before we get here, which means the code ran synchronously assert(calledBack) /* * Test error propagation */ fsStub.readdir = function (dir, cb) { cb(readdirError) } foo.filesAllCaps('./somedir', function (err, files) { assert.strictEqual(err, readdirError) }) console.log('*** All asserts passed ***') proxyquire-2.1.3/examples/async/foo.js000066400000000000000000000003761352426763500200430ustar00rootroot00000000000000var fs = require('fs') module.exports.filesAllCaps = function (dir, cb) { fs.readdir(dir, function (err, files) { if (err) cb(err) else { cb( null , files.map(function (f) { return f.toUpperCase() }) ) } }) } proxyquire-2.1.3/examples/example-utils.js000066400000000000000000000005171352426763500207310ustar00rootroot00000000000000var fs = require('fs') module.exports.listModuleAndTests = function (module, tests) { console.log( '\n**********\n' + '* Module:*\n' + '**********\n\n' + fs.readFileSync(module).toString() ) console.log( '**********\n' + '* Tests: *\n' + '**********\n' + fs.readFileSync(tests).toString() ) } proxyquire-2.1.3/examples/simple/000077500000000000000000000000001352426763500170705ustar00rootroot00000000000000proxyquire-2.1.3/examples/simple/foo.inlineoverride.test.js000066400000000000000000000014531352426763500242070ustar00rootroot00000000000000'use strict' var path = require('path') require('../example-utils').listModuleAndTests(path.resolve(__dirname, '/foo.js'), __filename) var proxyquire = require('../..') var assert = require('assert') var foo // no overrides yet, so path.extname behaves normally foo = proxyquire('./foo', {}) assert.strictEqual(foo.extnameAllCaps('file.txt'), '.TXT') // override path.extname foo = proxyquire('./foo', { path: { extname: function (file) { return 'Exterminate, exterminate the ' + file } } }) // path.extname now behaves as we told it to assert.strictEqual(foo.extnameAllCaps('file.txt'), 'EXTERMINATE, EXTERMINATE THE FILE.TXT') // path.basename on the other hand still functions as before assert.strictEqual(foo.basenameAllCaps('/a/b/file.txt'), 'FILE.TXT') console.log('*** All asserts passed ***') proxyquire-2.1.3/examples/simple/foo.js000066400000000000000000000003331352426763500202100ustar00rootroot00000000000000var path = require('path') module.exports.extnameAllCaps = function (file) { return path.extname(file).toUpperCase() } module.exports.basenameAllCaps = function (file) { return path.basename(file).toUpperCase() } proxyquire-2.1.3/examples/simple/foo.test.js000066400000000000000000000014701352426763500211710ustar00rootroot00000000000000'use strict' var path = require('path') require('../example-utils').listModuleAndTests(path.resolve(__dirname, '/foo.js'), __filename) var proxyquire = require('../..') var assert = require('assert') var pathStub = { } // when not overridden, path.extname behaves normally var foo = proxyquire('./foo', { path: pathStub }) assert.strictEqual(foo.extnameAllCaps('file.txt'), '.TXT') // override path.extname pathStub.extname = function (file) { return 'Exterminate, exterminate the ' + file } // path.extname now behaves as we told it to assert.strictEqual(foo.extnameAllCaps('file.txt'), 'EXTERMINATE, EXTERMINATE THE FILE.TXT') // path.basename and all other path module methods still function as before assert.strictEqual(foo.basenameAllCaps('/a/b/file.txt'), 'FILE.TXT') console.log('*** All asserts passed ***') proxyquire-2.1.3/examples/sinon/000077500000000000000000000000001352426763500167255ustar00rootroot00000000000000proxyquire-2.1.3/examples/sinon/foo-tests.js000066400000000000000000000052621352426763500212130ustar00rootroot00000000000000'use strict' /* * These examples demonstrate how to use proxyquire with Sinon.JS (). * Run these tests with mocha (). * e.g., mocha foo-tests.js */ var proxyquire = require('../..') var sinon = require('sinon') var assert = require('assert') var fs = require('fs') var path = require('path') var foo // Stubbing return values describe('when path.extname(file) returns ".markdown"', function () { var extnameStub var file = 'somefile' before(function () { extnameStub = sinon.stub(path, 'extname') foo = proxyquire('./foo', { path: { extname: extnameStub } }) extnameStub.withArgs(file).returns('.markdown') }) after(function () { path.extname.restore() }) it('extnameAllCaps returns ".MARKDOWN"', function () { assert.strictEqual(foo.extnameAllCaps(file), '.MARKDOWN') }) }) // Stubbing callbacks describe('when fs.readdir calls back with ["file1", "file2"]', function () { var readdirStub before(function () { readdirStub = sinon.stub(fs, 'readdir') foo = proxyquire('./foo', { fs: { readdir: readdirStub } }) readdirStub.withArgs('../simple').yields(null, ['file1', 'file2']) }) after(function () { fs.readdir.restore() }) it('filesAllCaps calls back with ["FILE1", "FILE2"]', function (done) { foo.filesAllCaps('../simple', function (err, files) { assert.strictEqual(err, null) assert.strictEqual(files[0], 'FILE1') assert.strictEqual(files[1], 'FILE2') done() }) }) }) describe('when fs.readdir returns an error', function () { var readdirError, readdirStub before(function () { readdirStub = sinon.stub(fs, 'readdir') foo = proxyquire('./foo', { fs: { readdir: readdirStub } }) readdirError = new Error('some error') readdirStub.withArgs('../simple').yields(readdirError, null) }) after(function () { fs.readdir.restore() }) it('filesAllCaps calls back with that error', function (done) { foo.filesAllCaps('../simple', function (err, files) { assert.strictEqual(err, readdirError) assert.strictEqual(files, null) done() }) }) }) // Spying describe('when calling filesAllCaps with "../simple"', function () { var readdirSpy before(function () { readdirSpy = sinon.spy(fs, 'readdir') foo = proxyquire('./foo', { fs: { readdir: readdirSpy } }) }) after(function () { fs.readdir.restore() }) it('calls fs.readdir with "../simple"', function (done) { foo.filesAllCaps('../simple', function (err, files) { assert.ifError(err) assert(fs.readdir.calledOnce) assert.strictEqual(fs.readdir.getCall(0).args[0], '../simple') done() }) }) }) proxyquire-2.1.3/examples/sinon/foo.js000066400000000000000000000005701352426763500200500ustar00rootroot00000000000000var fs = require('fs') var path = require('path') module.exports.filesAllCaps = function (dir, cb) { fs.readdir(dir, function (err, files) { if (err) cb(err) else { cb( null , files.map(function (f) { return f.toUpperCase() }) ) } }) } module.exports.extnameAllCaps = function (file) { return path.extname(file).toUpperCase() } proxyquire-2.1.3/index.js000066400000000000000000000007271352426763500154340ustar00rootroot00000000000000'use strict' var Proxyquire = require('./lib/proxyquire') // delete this module from the cache to force re-require in order to allow resolving test module via parent.module delete require.cache[require.resolve(__filename)] module.exports = new Proxyquire(module.parent) module.exports.compat = function () { throw new Error('Proxyquire compat mode has been removed. Please update your code to use the new API or pin the version in your package.json file to ~0.6') } proxyquire-2.1.3/lib/000077500000000000000000000000001352426763500145275ustar00rootroot00000000000000proxyquire-2.1.3/lib/is.js000066400000000000000000000005221352426763500154770ustar00rootroot00000000000000var is = {}; ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach(function (name) { is[name] = function (obj) { return Object.prototype.toString.call(obj) === '[object ' + name + ']' } }) is.Object = function (obj) { /* eslint no-new-object: "off" */ return obj === new Object(obj) } module.exports = is proxyquire-2.1.3/lib/proxyquire-error.js000066400000000000000000000004461352426763500204470ustar00rootroot00000000000000'use strict' var util = require('util') function ProxyquireError (msg) { this.name = 'ProxyquireError' Error.captureStackTrace(this, ProxyquireError) this.message = msg || 'An error occurred inside proxyquire.' } util.inherits(ProxyquireError, Error) module.exports = ProxyquireError proxyquire-2.1.3/lib/proxyquire.js000066400000000000000000000252511352426763500173210ustar00rootroot00000000000000'use strict' /* jshint laxbreak:true, loopfunc:true */ var Module = require('module') var path = require('path') var resolve = require('resolve') var ProxyquireError = require('./proxyquire-error') var is = require('./is') var assert = require('assert') var fillMissingKeys = require('fill-keys') var moduleNotFoundError = require('module-not-found-error') var hasOwnProperty = Object.prototype.hasOwnProperty function validateArguments (request, stubs) { var msg = (function getMessage () { if (!request) { return 'Missing argument: "request". Need it to resolve desired module.' } if (!stubs) { return 'Missing argument: "stubs". If no stubbing is needed, use regular require instead.' } if (!is.String(request)) { return 'Invalid argument: "request". Needs to be a requirable string that is the module to load.' } if (!is.Object(stubs)) { return 'Invalid argument: "stubs". Needs to be an object containing overrides e.g., {"path": { extname: function () { ... } } }.' } })() if (msg) throw new ProxyquireError(msg) } function Proxyquire (parent) { var self = this var fn = self.load.bind(self) var proto = Proxyquire.prototype this._parent = parent this._preserveCache = true Object.keys(proto) .forEach(function (key) { if (is.Function(proto[key])) fn[key] = self[key].bind(self) }) self.fn = fn return fn } /** * Disables call thru, which determines if keys of original modules will be used * when they weren't stubbed out. * @name noCallThru * @function * @private * @return {object} The proxyquire function to allow chaining */ Proxyquire.prototype.noCallThru = function () { this._noCallThru = true return this.fn } /** * Enables call thru, which determines if keys of original modules will be used * when they weren't stubbed out. * @name callThru * @function * @private * @return {object} The proxyquire function to allow chaining */ Proxyquire.prototype.callThru = function () { this._noCallThru = false return this.fn } /** * Will make proxyquire remove the requested modules from the `require.cache` in order to force * them to be reloaded the next time they are proxyquired. * This behavior differs from the way nodejs `require` works, but for some tests this maybe useful. * * @name noPreserveCache * @function * @private * @return {object} The proxyquire function to allow chaining */ Proxyquire.prototype.noPreserveCache = function () { this._preserveCache = false return this.fn } /** * Restores proxyquire caching behavior to match the one of nodejs `require` * * @name preserveCache * @function * @private * @return {object} The proxyquire function to allow chaining */ Proxyquire.prototype.preserveCache = function () { this._preserveCache = true return this.fn } /** * Loads a module using the given stubs instead of their normally resolved required modules. * @param request The requirable module path to load. * @param stubs The stubs to use. e.g., { "path": { extname: function () { ... } } } * @return {*} A newly resolved module with the given stubs. */ Proxyquire.prototype.load = function (request, stubs) { validateArguments(request, stubs) // Find out if any of the passed stubs are global overrides for (var key in stubs) { var stub = stubs[key] if (stub === null) continue if (typeof stub === 'undefined') { throw new ProxyquireError('Invalid stub: "' + key + '" cannot be undefined') } if (hasOwnProperty.call(stub, '@global')) { this._containsGlobal = true } if (hasOwnProperty.call(stub, '@runtimeGlobal')) { this._containsGlobal = true this._containsRuntimeGlobal = true } } // Ignore the module cache when return the requested module return this._withoutCache(this._parent, stubs, request, this._parent.require.bind(this._parent, request)) } // Resolves a stub relative to a module. // `baseModule` is the module we're resolving from. `pathToResolve` is the // module we want to resolve (i.e. the string passed to `require()`). Proxyquire.prototype._resolveModule = function (baseModule, pathToResolve, stubs) { try { return resolve.sync(pathToResolve, { basedir: path.dirname(baseModule), extensions: Object.keys(require.extensions), paths: Module.globalPaths }) } catch (err) { // If this is not a relative path (e.g. "foo" as opposed to "./foo"), and // we couldn't resolve it, then we just let the path through unchanged. // It's safe to do this, because if two different modules require "foo", // they both expect to get back the same thing. if (pathToResolve[0] !== '.') { return pathToResolve } // If `pathToResolve` is relative, then it is *not* safe to return it, // since a file in one directory that requires "./foo" expects to get // back a different module than one that requires "./foo" from another // directory. However, if !this._preserveCache, then we don't want to // throw, since we can resolve modules that don't exist. Resolve as // best we can. We also need to check if the relative module has @noCallThru. var resolvedPath = path.resolve(path.dirname(baseModule), pathToResolve) var moduleNoCallThru if (hasOwnProperty.call(stubs, pathToResolve) && stubs[pathToResolve]) { // pathToResolve is currently relative on stubs from _withoutCache() call moduleNoCallThru = hasOwnProperty.call(stubs[pathToResolve], '@noCallThru') ? stubs[pathToResolve]['@noCallThru'] : undefined } else if (hasOwnProperty.call(stubs, resolvedPath) && stubs[resolvedPath]) { // after _withoutCache() alters stubs paths to be absolute moduleNoCallThru = hasOwnProperty.call(stubs[resolvedPath], '@noCallThru') ? stubs[resolvedPath]['@noCallThru'] : undefined } if (!this._preserveCache || this._noCallThru || moduleNoCallThru) { return resolvedPath } throw err } } // This replaces a module's require function Proxyquire.prototype._require = function (module, stubs, path) { assert(typeof path === 'string', 'path must be a string') assert(path, 'missing path') var resolvedPath = this._resolveModule(module.filename, path, stubs) if (hasOwnProperty.call(stubs, resolvedPath)) { var stub = stubs[resolvedPath] if (stub === null) { // Mimic the module-not-found exception thrown by node.js. throw moduleNotFoundError(path) } if (hasOwnProperty.call(stub, '@noCallThru') ? !stub['@noCallThru'] : !this._noCallThru) { fillMissingKeys(stub, Module._load(path, module)) } // We are top level or this stub is marked as global if (module.parent === this._parent || hasOwnProperty.call(stub, '@global') || hasOwnProperty.call(stub, '@runtimeGlobal')) { return stub } } // Only ignore the cache if we have global stubs if (this._containsRuntimeGlobal) { return this._withoutCache(module, stubs, path, Module._load.bind(Module, path, module)) } else { return Module._load(path, module) } } Proxyquire.prototype._withoutCache = function (module, stubs, path, func) { // Temporarily disable the cache - either per-module or globally if we have global stubs var restoreCache = this._disableCache(module, path) var resolvedPath = Module._resolveFilename(path, module) // Resolve all stubs to absolute paths. stubs = Object.keys(stubs) .reduce(function (result, stubPath) { var resolvedStubPath = this._resolveModule(resolvedPath, stubPath, stubs) result[resolvedStubPath] = stubs[stubPath] return result }.bind(this), {}) // Override all require extension handlers var restoreExtensionHandlers = this._overrideExtensionHandlers(module, stubs) try { // Execute the function that needs the module cache disabled return func() } finally { // Restore the cache if we are preserving it if (this._preserveCache) { restoreCache() } else { var ids = [resolvedPath].concat(Object.keys(stubs).filter(Boolean)) ids.forEach(function (id) { delete require.cache[id] }) } // Finally restore the original extension handlers restoreExtensionHandlers() } } Proxyquire.prototype._disableCache = function (module, path) { if (this._containsGlobal) { // empty the require cache because if we are stubbing C but requiring A, // and if A requires B and B requires C, then B and C might be cached already // and we'll never get the chance to return our stub return this._disableGlobalCache() } // Temporarily delete the SUT from the require cache return this._disableModuleCache(path, module) } Proxyquire.prototype._disableGlobalCache = function () { var cache = require.cache require.cache = Module._cache = {} for (var id in cache) { // Keep native modules (i.e. `.node` files). // Otherwise, Node.js would throw a “Module did not self-register” // error upon requiring it a second time. // See https://github.com/nodejs/node/issues/5016. if (/\.node$/.test(id)) { require.cache[id] = cache[id] } } // Return a function that will undo what we just did return function () { // Keep native modules which were added to the cache in the meantime. for (var id in require.cache) { if (/\.node$/.test(id)) { cache[id] = require.cache[id] } } require.cache = Module._cache = cache } } Proxyquire.prototype._disableModuleCache = function (path, module) { // Find the ID (location) of the SUT, relative to the parent var id = Module._resolveFilename(path, module) var cached = Module._cache[id] delete Module._cache[id] // Return a function that will undo what we just did return function () { if (cached) { Module._cache[id] = cached } else { delete Module._cache[id] } } } Proxyquire.prototype._overrideExtensionHandlers = function (module, resolvedStubs) { /* eslint node/no-deprecated-api: [error, {ignoreGlobalItems: ["require.extensions"]}] */ var originalExtensions = {} var self = this Object.keys(require.extensions).forEach(function (extension) { // Store the original so we can restore it later if (!originalExtensions[extension]) { originalExtensions[extension] = require.extensions[extension] } // Override the default handler for the requested file extension require.extensions[extension] = function (module, filename) { // Override the require method for this module module.require = self._require.bind(self, module, resolvedStubs) return originalExtensions[extension](module, filename) } }) // Return a function that will undo what we just did return function () { Object.keys(originalExtensions).forEach(function (extension) { require.extensions[extension] = originalExtensions[extension] }) } } module.exports = Proxyquire proxyquire-2.1.3/package.json000066400000000000000000000015171352426763500162530ustar00rootroot00000000000000{ "name": "proxyquire", "version": "2.1.3", "description": "Proxies nodejs require in order to allow overriding dependencies during testing.", "main": "index.js", "scripts": { "test": "standard && mocha" }, "repository": { "type": "git", "url": "https://github.com/thlorenz/proxyquire.git" }, "keywords": [ "require", "dependency", "injection", "di", "inject", "swap", "test", "mock", "stub" ], "author": "Thorsten Lorenz", "license": "MIT", "devDependencies": { "mocha": "^5.2.0", "native-hello-world": "^1.0.0", "should": "^13.2.3", "sinon": "^7.3.2", "standard": "^13.0.1" }, "dependencies": { "fill-keys": "^1.0.2", "module-not-found-error": "^1.0.1", "resolve": "^1.11.1" }, "standard": { "env": [ "mocha" ] } } proxyquire-2.1.3/test/000077500000000000000000000000001352426763500147405ustar00rootroot00000000000000proxyquire-2.1.3/test/mocha.opts000066400000000000000000000000661352426763500167400ustar00rootroot00000000000000--require should --reporter spec --ui bdd --growl testproxyquire-2.1.3/test/proxyquire-api.js000066400000000000000000000017611352426763500203010ustar00rootroot00000000000000'use strict' var assert = require('assert') var realFoo = require('./samples/foo') var stubs = { path: { extname: function () {}, basename: function () {} } } describe('api', function () { describe('default export', function () { var proxyquire = require('..') it('proxyquire can load', function () { var proxiedFoo = proxyquire.load('./samples/foo', stubs) assert.strictEqual(typeof proxiedFoo, 'object') assert.notStrictEqual(realFoo, proxiedFoo) }) it('proxyquire can callThru and then load', function () { var proxiedFoo = proxyquire.callThru().load('./samples/foo', stubs) assert.strictEqual(typeof proxiedFoo, 'object') assert.notStrictEqual(realFoo, proxiedFoo) }) it('proxyquire can noCallThru and then load', function () { var proxiedFoo = proxyquire.noCallThru().load('./samples/foo', stubs) assert.strictEqual(typeof proxiedFoo, 'object') assert.notStrictEqual(realFoo, proxiedFoo) }) }) }) proxyquire-2.1.3/test/proxyquire-argumentvalidation.js000066400000000000000000000035401352426763500234220ustar00rootroot00000000000000'use strict' var assert = require('assert') var proxyquire = require('..') describe('Illegal parameters to resolve give meaningful errors', function () { var bar = { bar: function () { return 'bar' } } function throws (action, regex) { assert.throws(action, function (err) { return err.name === 'ProxyquireError' && regex.test(err.message) && regex.test(err.toString()) }) } describe('when I pass no request', function () { function act () { proxyquire(null, {}) } it('throws an exception explaining that a request path must be provided', function () { throws(act, /missing argument: "request"/i) }) }) describe('when I pass an object as a request', function () { function act () { proxyquire({ }, { './bar': bar }) } it('throws an exception explaining that request needs to be a requirable string', function () { throws(act, /invalid argument: "request".+needs to be a requirable string/i) }) }) describe('when I pass no stubs', function () { function act () { proxyquire('./samples/foo') } it('throws an exception explaining that resolve without stubs makes no sense', function () { throws(act, /missing argument: "stubs".+use regular require instead/i) }) }) describe('when I pass a string as stubs', function () { function act () { proxyquire('./samples/foo', 'stubs') } it('throws an exception explaining that stubs need to be an object', function () { throws(act, /invalid argument: "stubs".+needs to be an object/i) }) }) describe('when I pass an undefined stub', function () { function act () { proxyquire('./samples/foo', { myStub: undefined }) } it('throws an exception with the stub key', function () { throws(act, /Invalid stub: "myStub" cannot be undefined/) }) }) }) proxyquire-2.1.3/test/proxyquire-cache.js000066400000000000000000000076271352426763500206020ustar00rootroot00000000000000'use strict' var assert = require('assert') describe('Proxyquire', function () { describe('load()', function () { it('defaults to preserving the cache', function () { var original = require('./samples/foo') original.state = 'cached' var proxyquire = require('..') proxyquire('./samples/foo', { path: { } }) var foo = require('./samples/foo') assert.strictEqual('cached', foo.state) assert.strictEqual(foo, original) }) it('does not pollute the cache when module is proxyquired before it is loaded', function () { var proxyquire = require('..') proxyquire('./samples/no-call-thru-test', { './required': false }) var original = require('./samples/no-call-thru-test') assert.strictEqual(original.original, true) }) }) describe('preserveCache()', function () { it('returns a reference to itself, so it can be chained', function () { var proxyquire = require('..') assert.strictEqual(proxyquire.preserveCache(), proxyquire) }) it('has Proxyquire restore the cache for the module', function () { var original = require('./samples/foo') original.state = 'cached' var proxyquire = require('..') proxyquire.preserveCache() proxyquire.load('./samples/foo', { path: { } }) var foo = require('./samples/foo') assert.strictEqual('cached', foo.state) assert.strictEqual(foo, original) }) it('allows Singletons to function properly', function () { var original = require('./samples/foo-singleton').getInstance() var proxyquire = require('..') proxyquire.preserveCache() proxyquire.load('./samples/foo-singleton', { path: { } }).getInstance() var fooSingleton = require('./samples/foo-singleton').getInstance() assert.strictEqual(fooSingleton, original) }) }) describe('noPreserveCache()', function () { it('returns a reference to itself, so it can be chained', function () { var proxyquire = require('..') assert.strictEqual(proxyquire.noPreserveCache(), proxyquire) }) it('forces subsequent requires to reload the proxied module', function () { var original = require('./samples/foo') original.state = 'cached' var proxyquire = require('..') proxyquire.load('./samples/foo', { path: { } }) var cacheFoo = require('./samples/foo') assert.strictEqual('cached', cacheFoo.state) assert.strictEqual(cacheFoo, original) proxyquire.noPreserveCache() proxyquire.load('./samples/foo', { path: { } }) var foo = require('./samples/foo') assert.strictEqual('', foo.state) assert.notStrictEqual(foo, original) }) it('deletes the require.cache for the module being stubbed', function () { var proxyquire = require('..').noPreserveCache() proxyquire.load('./samples/foo', { path: { } }) assert.strictEqual(undefined, require.cache[require.resolve('./samples/foo')]) }) it('deletes the require.cache for the stubs', function () { var proxyquire = require('..').noPreserveCache() var bar = {} var foo = proxyquire.load('./samples/cache/foo', { './bar': bar }) bar.f.g = function () { return 'a' } bar.h = function () { return 'a' } assert.strictEqual(foo.bar.f.g(), 'a') assert.strictEqual(foo.bar.h(), 'a') foo = proxyquire.load('./samples/cache/foo', { './bar': {} }) assert.strictEqual(foo.bar.h(), 'h') assert.strictEqual(foo.bar.f.g(), 'g') assert.strictEqual(undefined, require.cache[require.resolve('./samples/cache/foo')]) assert.strictEqual(undefined, require.cache[require.resolve('./samples/cache/bar')]) }) it('silences errors when stub lookups fail', function () { var proxyquire = require('..').noPreserveCache() assert.doesNotThrow(function () { proxyquire.load('./samples/cache/foo', { './does-not-exist': {} }) }) }) }) }) proxyquire-2.1.3/test/proxyquire-compat.js000066400000000000000000000004301352426763500210030ustar00rootroot00000000000000'use strict' /* jshint asi:true */ var proxyquire = require('..') describe('when I try to use compat mode', function () { it('should let me know that I need to fix my code or downgrade', function () { proxyquire.compat.should.throw(/compat mode has been removed/) }) }) proxyquire-2.1.3/test/proxyquire-extensions.js000066400000000000000000000013611352426763500217230ustar00rootroot00000000000000'use strict' var proxyquire = require('..').noCallThru() describe('when I require stubs with different extensions', function () { var res before(function () { res = proxyquire('./samples/extensions', { fs: 'fs.export', fn: function () { return 'fn.result' }, '/fs.json': 'fs.json.export', '/fn.node': 'fn.node.export' }) }) it('intercepts [] object', function () { res.fs.should.equal('fs.export') }) it('intercepts [] function', function () { res.fn().should.equal('fn.result') }) it('intercepts [.json] object', function () { res['/fs.json'].should.equal('fs.json.export') }) it('intercepts [.node] object', function () { res['/fn.node'].should.equal('fn.node.export') }) }) proxyquire-2.1.3/test/proxyquire-global.js000066400000000000000000000036041352426763500207660ustar00rootroot00000000000000'use strict' var assert = require('assert') var realFoo = require('./samples/global/foo') var proxyquire = require('..') describe('global flags set', function () { it('should override require globally', function () { var stubs = { './baz': { method: function () { return true }, '@global': true } } var proxiedFoo = proxyquire('./samples/global/foo', stubs) assert.strictEqual(realFoo(), false) assert.strictEqual(proxiedFoo(), true) }) it('should override require globally even when require\'s execution is deferred', function () { var stubs = { './baz': { method: function () { return true }, '@runtimeGlobal': true } } var proxiedFoo = proxyquire('./samples/global/foo-deferred', stubs) assert.strictEqual(realFoo(), false) assert.strictEqual(proxiedFoo(), true) }) it('should not throw when a native module is required a second time', function () { var stubs = { foo: { '@global': true } } proxyquire('native-hello-world', stubs) proxyquire('native-hello-world', stubs) }) }) describe('global flags not set', function () { it('should not override require globally', function () { var stubs = { './baz': { method: function () { return true } } } var proxiedFoo = proxyquire('./samples/global/foo', stubs) assert.strictEqual(realFoo(), false) assert.strictEqual(proxiedFoo(), false) }) it('should not override require globally even when require\'s execution is deferred', function () { var stubs = { './baz': { method: function () { return true } } } var proxiedFoo = proxyquire('./samples/global/foo-deferred', stubs) assert.strictEqual(realFoo(), false) assert.strictEqual(proxiedFoo(), false) }) }) proxyquire-2.1.3/test/proxyquire-independence.js000066400000000000000000000022401352426763500221420ustar00rootroot00000000000000/* jshint asi:true */ 'use strict' var assert = require('assert') var proxyquire = require('..') describe('Multiple requires of same module don\'t affect each other', function () { describe('Given I require foo stubbed with bar1 as foo1 and foo stubbed with bar2 as foo2', function () { var foo1 var foo2 var bar1 = { bar: function () { return 'bar1' } } var bar2 = { bar: function () { return 'bar2' } } before(function () { foo1 = proxyquire('./samples/foo', { './bar': bar1 }) foo2 = proxyquire('./samples/foo', { './bar': bar2 }) }) it('foo1.bigBar() == "BAR1"', function () { assert.strictEqual(foo1.bigBar(), 'BAR1') }) it('foo2.bigBar() == "BAR2"', function () { assert.strictEqual(foo2.bigBar(), 'BAR2') }) describe('and I change bar1.bar() to return barone', function () { before(function () { bar1.bar = function () { return 'barone' } }) it('foo1.bigBar() == "BARONE"', function () { assert.strictEqual(foo1.bigBar(), 'BARONE') }) it('foo2.bigBar() == "BAR2"', function () { assert.strictEqual(foo2.bigBar(), 'BAR2') }) }) }) }) proxyquire-2.1.3/test/proxyquire-non-object.js000066400000000000000000000064741352426763500215740ustar00rootroot00000000000000'use strict' var assert = require('assert') var proxyquire = require('..') var stats = require('./samples/stats') describe('Given foo requires the boof, foonum and foobool modules and boof is a string, foonum is a Number and foobool is a bool', function () { var foo var boofber = 'a_string' var foonumber = 4 var fooboolber = false var fooarray = ['x', 'y', 'z'] describe('When I resolve foo with boofber stub as boof.', function () { before(function () { stats.reset() foo = proxyquire('./samples/foo', { './boof': boofber }) }) it('foo is required 1 times', function () { assert.strictEqual(stats.fooRequires(), 1) }) describe('foo\'s boof is boofber', function () { it('foo.boof == boofber', function () { assert.strictEqual(foo.boof, boofber) }) }) }) describe('When I resolve foo with foonumber stub as foonum.', function () { before(function () { stats.reset() foo = proxyquire('./samples/foo', { './foonum': foonumber }) }) it('foo is required 1 times', function () { assert.strictEqual(stats.fooRequires(), 1) }) describe('foo\'s foonum is foonumber', function () { it('foo.foonum == foonumber', function () { assert.strictEqual(foo.foonum, foonumber) }) }) }) describe('When I resolve foo with fooboolber stub as foobool.', function () { before(function () { stats.reset() foo = proxyquire('./samples/foo', { './foobool': fooboolber }) }) it('foo is required 1 times', function () { assert.strictEqual(stats.fooRequires(), 1) }) describe('foo\'s foobool is fooboolber', function () { it('foo.foobool == fooboolber', function () { assert.strictEqual(foo.foobool, fooboolber) }) }) }) describe('When I resolve foo with ./fooarray stub as fooarray.', function () { before(function () { stats.reset() foo = proxyquire('./samples/foo', { './fooarray': fooarray }) }) it('foo is required 1 times', function () { assert.strictEqual(stats.fooRequires(), 1) }) describe('foo\'s fooarray is fooarray', function () { it('foo.fooarray is fooarray', function () { assert.deepStrictEqual(foo.fooarray, ['x', 'y', 'z']) }) }) }) describe('When I resolve foo with ./fooarray stub as empty.', function () { before(function () { stats.reset() foo = proxyquire('./samples/foo', { './fooarray': [] }) }) it('foo is required 1 times', function () { assert.strictEqual(stats.fooRequires(), 1) }) describe('foo\'s fooarray is the original', function () { it('foo.fooarray is empty', function () { assert.deepStrictEqual(foo.fooarray, ['a', 'b', 'c']) }) }) }) describe('When I resolve foo with ./fooarray stub as empty with @noCallThru.', function () { before(function () { stats.reset() var empty = [] Object.defineProperty(empty, '@noCallThru', { value: true }) foo = proxyquire('./samples/foo', { './fooarray': empty }) }) it('foo is required 1 times', function () { assert.strictEqual(stats.fooRequires(), 1) }) describe('foo\'s fooarray is empty', function () { it('foo.fooarray is empty', function () { assert.deepStrictEqual(foo.fooarray, []) }) }) }) }) proxyquire-2.1.3/test/proxyquire-notexisting.js000066400000000000000000000031621352426763500221000ustar00rootroot00000000000000'use strict' var assert = require('assert') var proxyquire = require('..') var path = require('path') var fooPath = path.join(__dirname, './samples/notexisting/foo.js') var fooRelativePath = path.join(__dirname, './samples/notexisting/foo-relative.js') describe('When resolving foo that requires stubbed /not/existing/bar.json', function () { it('throws an error', function () { assert.throws(function () { proxyquire(fooPath, { '/not/existing/bar.json': { config: 'bar\'s config' } }) }) }) }) describe('When resolving foo that requires stubbed /not/existing/bar.json with @noCallThru', function () { it('resolves foo with stubbed bar', function () { var foo = proxyquire(fooPath, { '/not/existing/bar.json': { config: 'bar\'s config', '@noCallThru': true } }) assert.strictEqual(foo.config, 'bar\'s config') }) }) describe('When resolving foo that requires stubbed /not/existing/bar.json with noCallThru()', function () { it('resolves foo with stubbed bar', function () { proxyquire.noCallThru() var foo = proxyquire(fooPath, { '/not/existing/bar.json': { config: 'bar\'s config' } }) assert.strictEqual(foo.config, 'bar\'s config') proxyquire.callThru() }) }) describe('When resolving foo-relative that requires relative stubbed ../not/existing/bar.json with @noCallThru', function () { it('resolves foo-relative with stubbed bar', function () { var fooRelative = proxyquire(fooRelativePath, { '../not/existing/bar.json': { config: 'bar\'s config', '@noCallThru': true } }) assert.strictEqual(fooRelative.config, 'bar\'s config') }) }) proxyquire-2.1.3/test/proxyquire-relative-paths.js000066400000000000000000000005701352426763500224550ustar00rootroot00000000000000'use strict' /* jshint asi:true */ var proxyquire = require('..') describe('When requiring relative paths, they should be relative to the proxyrequired module', function () { it('should return the correct result', function () { var result = proxyquire('./samples/relative-paths/a/index.js', { './util': { c: 'c' } }) result.should.eql({ a: 'a', c: 'c' }) }) }) proxyquire-2.1.3/test/proxyquire-remove.js000066400000000000000000000013131352426763500210160ustar00rootroot00000000000000'use strict' /* jshint asi:true */ var assert = require('assert') var proxyquire = require('..') var path = require('path') var fooPath = path.join(__dirname, './samples/foo.js') describe('When resolving foo that requires nulled file package', function () { it('throws an error', function () { assert.throws(function () { proxyquire(fooPath, { path: null }) }, function (error) { return error.code === 'MODULE_NOT_FOUND' }) }) }) describe('When resolving foo that optionally requires nulled crypto package', function () { it('catches when resolving crypto', function () { var foo = proxyquire(fooPath, { crypto: null }) assert.strictEqual(foo.bigCrypto(), 'caught') }) }) proxyquire-2.1.3/test/proxyquire-sub-dependencies.js000066400000000000000000000012551352426763500227430ustar00rootroot00000000000000'use strict' /* jshint asi:true */ var assert = require('assert') var proxyquire = require('..') describe('When resolving foo that requires bar and stubbed baz where bar requires unstubbed baz', function () { var bazStub, foo, baz before(function () { bazStub = { testexport: 'stubbed' } foo = proxyquire('./samples/sub-dependencies/foo', { './baz': bazStub }) baz = require('./samples/sub-dependencies/baz') }) it('does not stub baz in bar', function () { assert.strictEqual(foo.bar.baz.testexport, 'test') }) it('does not affect a normal baz import', function () { assert.strictEqual(baz.testexport, 'test') }) }) proxyquire-2.1.3/test/proxyquire.js000066400000000000000000000134411352426763500175300ustar00rootroot00000000000000/* jshint asi:true */ 'use strict' var assert = require('assert') var proxyquire = require('..') var stats = require('./samples/stats') describe('Given foo requires the bar and path modules and bar.bar() returns "bar"', function () { var file = '/folder/test.ext' var foo var foober var barber = { bar: function () { return 'barber' } } describe('When I resolve foo with no overrides to bar as foo and resolve foo with barber stub as foober.', function () { before(function () { stats.reset() foo = proxyquire('./samples/foo', { './bar': { /* no overrides */ } }) foober = proxyquire('./samples/foo', { './bar': barber }) }) it('foo is required 2 times', function () { assert.strictEqual(stats.fooRequires(), 2) }) describe('foo\'s bar is unchanged', function () { it('foo.bigBar() == "BAR"', function () { assert.strictEqual(foo.bigBar(), 'BAR') }) }) describe('only stubbed modules have overrides in foober', function () { it('foober.bigBar() == "BARBER"', function () { assert.strictEqual(foober.bigBar(), 'BARBER') }) it('foober.bigExt("/folder/test.ext") == ".EXT"', function () { assert.strictEqual(foober.bigExt(file), '.EXT') }) it('foober.bigBas("/folder/test.ext") == "TEST.EXT"', function () { assert.strictEqual(foober.bigBas(file), 'TEST.EXT') }) }) describe('when I override keys of stubs after resolve', function () { before(function () { barber.bar = function () { return 'friseur' } barber.rab = function () { return 'rabarber' } }) it('overrides behavior when module is required inside function call', function () { assert.strictEqual(foober.bigBar(), 'FRISEUR') }) it('overrides behavior when module is required on top of file', function () { assert.strictEqual(foober.bigRab(), 'RABARBER') }) describe('and then delete overrides of stubs after resolve', function () { beforeEach(function () { delete barber.bar delete barber.rab }) it('reverts to original behavior when module is required inside function call', function () { assert.strictEqual(foober.bigBar(), 'BAR') }) it('doesn\'t properly revert to original behavior when module is required on top of file ', function () { assert.throws(foober.bigRab) }) }) }) }) describe('When foo.bigExt() returns capitalized path.extname and foo.bigBas() returns capitalized path.basename', function () { describe('and path.extname(file) is stubbed to return "override " + file', function () { describe('and callThru was not changed globally or for path module', function () { before(function () { foo = proxyquire('./samples/foo', { path: { extname: function (file) { return 'override ' + file } } }) }) it('foo.bigExt(file) == "OVERRIDE /FOLDER/TEST.EXT"', function () { assert.strictEqual(foo.bigExt(file), 'OVERRIDE /FOLDER/TEST.EXT') }) it('foo.bigBas(file) == "TEST.EXT"', function () { assert.strictEqual(foo.bigBas(file), 'TEST.EXT') }) }) describe('and callThru is turned off for path module', function () { before(function () { foo = proxyquire('./samples/foo', { path: { extname: function (file) { return 'override ' + file }, '@noCallThru': true } }) }) it('foo.bigExt(file) == "OVERRIDE /FOLDER/TEST.EXT"', function () { assert.strictEqual(foo.bigExt(file), 'OVERRIDE /FOLDER/TEST.EXT') }) it('foo.bigBas(file) throws', function () { assert.throws(foo.bigBas) }) }) describe('and callThru was turned off globally', function () { var $proxyquire before(function () { $proxyquire = proxyquire.noCallThru() }) describe('and not changed for path module', function () { before(function () { foo = $proxyquire('./samples/foo', { path: { extname: function (file) { return 'override ' + file } } }) }) it('foo.bigExt(file) == "OVERRIDE /FOLDER/TEST.EXT"', function () { assert.strictEqual(foo.bigExt(file), 'OVERRIDE /FOLDER/TEST.EXT') }) it('foo.bigBas(file) throws', function () { assert.throws(foo.bigBas) }) }) describe('and turned back on for path module', function () { before(function () { foo = $proxyquire('./samples/foo', { path: { extname: function (file) { return 'override ' + file }, '@noCallThru': false } }) }) it('foo.bigExt(file) == "OVERRIDE /FOLDER/TEST.EXT"', function () { assert.strictEqual(foo.bigExt(file), 'OVERRIDE /FOLDER/TEST.EXT') }) it('foo.bigBas(file) == "TEST.EXT"', function () { assert.strictEqual(foo.bigBas(file), 'TEST.EXT') }) }) describe('and turned back on globally', function () { before(function () { foo = $proxyquire .callThru() .load('./samples/foo', { path: { extname: function (file) { return 'override ' + file } } }) }) it('foo.bigExt(file) == "OVERRIDE /FOLDER/TEST.EXT"', function () { assert.strictEqual(foo.bigExt(file), 'OVERRIDE /FOLDER/TEST.EXT') }) it('foo.bigBas(file) == "TEST.EXT"', function () { assert.strictEqual(foo.bigBas(file), 'TEST.EXT') }) }) }) }) }) }) proxyquire-2.1.3/test/samples/000077500000000000000000000000001352426763500164045ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/bar.js000066400000000000000000000001601352426763500175030ustar00rootroot00000000000000function bar () { return 'bar' } function rab () { return 'rab' } module.exports = { bar: bar, rab: rab } proxyquire-2.1.3/test/samples/boof.js000066400000000000000000000000301352426763500176600ustar00rootroot00000000000000module.exports = 'boof' proxyquire-2.1.3/test/samples/cache/000077500000000000000000000000001352426763500174475ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/cache/bar.js000066400000000000000000000001631352426763500205510ustar00rootroot00000000000000module.exports = { f: { g: function () { return 'g' } }, h: function () { return 'h' } } proxyquire-2.1.3/test/samples/cache/foo.js000066400000000000000000000000721352426763500205670ustar00rootroot00000000000000var bar = require('./bar') module.exports = { bar: bar } proxyquire-2.1.3/test/samples/extensions.js000066400000000000000000000002041352426763500211350ustar00rootroot00000000000000module.exports = { fs: require('fs'), fn: require('fn'), '/fs.json': require('/fs.json'), '/fn.node': require('/fn.node') } proxyquire-2.1.3/test/samples/foo-singleton.js000066400000000000000000000002541352426763500215260ustar00rootroot00000000000000function FooSingleton () { } var instance = null exports.getInstance = function () { if (instance === null) { instance = new FooSingleton() } return instance } proxyquire-2.1.3/test/samples/foo.js000066400000000000000000000016111352426763500175240ustar00rootroot00000000000000var stats = require('./stats') var bar = require('./bar') var boof = require('./boof') var foonum = require('./foonum') var foobool = require('./foobool') var fooarray = require('./fooarray') var path = require('path') var crypto // Require if present. try { crypto = require('crypto') } catch (e) { crypto = 'caught' } stats.incFooRequires() function bigBar () { // inline require return require('./bar').bar().toUpperCase() } function bigRab () { // module wide require return bar.rab().toUpperCase() } function bigExt (file) { return path.extname(file).toUpperCase() } function bigBas (file) { return path.basename(file).toUpperCase() } function bigCrypto () { return crypto } module.exports = { bigBar: bigBar, bigRab: bigRab, bigExt: bigExt, bigBas: bigBas, boof: boof, foonum: foonum, foobool: foobool, fooarray: fooarray, bigCrypto: bigCrypto, state: '' } proxyquire-2.1.3/test/samples/fooarray.js000066400000000000000000000000411352426763500205570ustar00rootroot00000000000000module.exports = ['a', 'b', 'c'] proxyquire-2.1.3/test/samples/foobool.js000066400000000000000000000000261352426763500203770ustar00rootroot00000000000000module.exports = true proxyquire-2.1.3/test/samples/foonum.js000066400000000000000000000000231352426763500202400ustar00rootroot00000000000000module.exports = 3 proxyquire-2.1.3/test/samples/global/000077500000000000000000000000001352426763500176445ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/global/bar.js000066400000000000000000000001231352426763500207420ustar00rootroot00000000000000var baz = require('./baz') module.exports = function () { return baz.method() } proxyquire-2.1.3/test/samples/global/baz.js000066400000000000000000000001021352426763500207470ustar00rootroot00000000000000module.exports = { method: function () { return false } } proxyquire-2.1.3/test/samples/global/foo-deferred.js000066400000000000000000000001171352426763500225420ustar00rootroot00000000000000 module.exports = function () { var bar = require('./bar') return bar() } proxyquire-2.1.3/test/samples/global/foo.js000066400000000000000000000001141352426763500207610ustar00rootroot00000000000000var bar = require('./bar') module.exports = function () { return bar() } proxyquire-2.1.3/test/samples/no-call-thru-test/000077500000000000000000000000001352426763500216665ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/no-call-thru-test/index.js000066400000000000000000000000511352426763500233270ustar00rootroot00000000000000exports.original = require('./required') proxyquire-2.1.3/test/samples/no-call-thru-test/required.js000066400000000000000000000000261352426763500240420ustar00rootroot00000000000000module.exports = true proxyquire-2.1.3/test/samples/notexisting/000077500000000000000000000000001352426763500207575ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/notexisting/foo-relative.js000066400000000000000000000001311352426763500237040ustar00rootroot00000000000000var bar = require('../not/existing/bar.json') module.exports = { config: bar.config } proxyquire-2.1.3/test/samples/notexisting/foo.js000066400000000000000000000001271352426763500221000ustar00rootroot00000000000000var bar = require('/not/existing/bar.json') module.exports = { config: bar.config } proxyquire-2.1.3/test/samples/relative-paths/000077500000000000000000000000001352426763500213345ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/relative-paths/a/000077500000000000000000000000001352426763500215545ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/relative-paths/a/index.js000066400000000000000000000001041352426763500232140ustar00rootroot00000000000000var util = require('./util') require('../b') module.exports = util proxyquire-2.1.3/test/samples/relative-paths/a/util.js000066400000000000000000000000201352426763500230570ustar00rootroot00000000000000exports.a = 'a' proxyquire-2.1.3/test/samples/relative-paths/b/000077500000000000000000000000001352426763500215555ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/relative-paths/b/index.js000066400000000000000000000000221352426763500232140ustar00rootroot00000000000000require('./util') proxyquire-2.1.3/test/samples/relative-paths/b/util.js000066400000000000000000000000201352426763500230600ustar00rootroot00000000000000exports.b = 'b' proxyquire-2.1.3/test/samples/stats.js000066400000000000000000000002661352426763500201040ustar00rootroot00000000000000var fooRequires = 0 module.exports = { fooRequires: function () { return fooRequires }, incFooRequires: function () { fooRequires++ }, reset: function () { fooRequires = 0 } } proxyquire-2.1.3/test/samples/sub-dependencies/000077500000000000000000000000001352426763500216215ustar00rootroot00000000000000proxyquire-2.1.3/test/samples/sub-dependencies/bar.js000066400000000000000000000000741352426763500227240ustar00rootroot00000000000000var baz = require('./baz') module.exports = { baz: baz } proxyquire-2.1.3/test/samples/sub-dependencies/baz.js000066400000000000000000000000521352426763500227300ustar00rootroot00000000000000module.exports = { testexport: 'test' } proxyquire-2.1.3/test/samples/sub-dependencies/foo.js000066400000000000000000000001431352426763500227400ustar00rootroot00000000000000var baz = require('./baz') var bar = require('./bar') module.exports = { baz: baz, bar: bar }