🔮 Proxies nodejs require in order to allow overriding dependencies during testing.

Related tags

Assertion proxyquire
Overview

proxyquire Build Status

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, a proxyquire for browserify v2 or 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:

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:

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:

var get    = require('simple-get');
var assert = require('assert');

module.exports = function fetch (callback) {
  get('https://api/users', callback);
};

get.test.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

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 your stub is a class or class instance rather than a plain object, you should disable callThru to ensure that it is passed through with the correct prototype.

class MockClass {
  static '@noCallThru' = true;
}

var foo = proxyquire('./foo', {
  './my-class': MockClass
});
class MockClass {
  get '@noCallThru'() {
    return true;
  }
}

var foo = proxyquire('./foo', {
  './my-class-instance': new MockClass()
});

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:

var foo = proxyquire('./foo', {
  path: {
      extname: function (file) { ... }
    , '@noCallThru': true
  }
});

Prevent call thru for all future stubs resolved by a proxyquire instance

// 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

proxyquire.callThru();

Call thru configurations per module override callThru():

Passing @noCallThru: false when configuring modules will override noCallThru():

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

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:

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.

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.

// 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.

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

// 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 bazStub = {
  method: function() {
    console.info('goodbye');
  }
};
  
var stubs = {
  './baz': Object.assign(bazStub, {'@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:

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:

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:

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:

function foo () {}
proxyquire('./bar', {
  foo: Object.assign(foo, {'@global': true})
});

And if your stub is in a separate module where module.exports = foo:

var foostub = require('../stubs/foostub');
proxyquire('bar', {
  foo: Object.assign(foostub, {'@global': true})
});

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:

// 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:

// 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 or look through the tests

Specific Examples:

Comments
  • Calls the original function even though stubbing the original function using proxyquire

    Calls the original function even though stubbing the original function using proxyquire

    I have a module db.js which contains the following code:

    var sql = require('mssql');
    var async = require('async');
    
    module.exports = {
        getDetails: function(number, callback) {
    
        async.parallel({
                general: function(callback) {
                    getGeneral(number, callback);
                },
                preferences: function(callback) {
                    getPref(number, callback);
                }
            },
            function(err, results) {
                if (err) {
                    logger.error(err);
                    throw err;
                }
                callback(results);
            });
    }
    };
    
    function getGeneral(number, callback) {
        var mainconnection = new sql.Connection(dbCredentials[1].generalDBConfig, function(err) {
            var request = new sql.Request(mainconnection);
            request.input('number', sql.BigInt, number);
            request.execute('[number].[genral_get]', function(err, recordsets) {
                if (err) {
                    logger.error(err);
                }
                var gen = {};
                var spResult = recordsets[0];
                if (spResult[0] != null) {
                    spResult.forEach(function(record) {
                        var test = {};
                        gen[record.genCode] = record.genValue;
                    });
    
                    callback(null, gen);
                } else {
                    callback(null, null);
                }
    
            });
    
        });
    }
    
    function getPref(number, callback) {
        var mainconnection = new sql.Connection(dbCredentials[0].prefDBConfig, function(err) {
            var request = new sql.Request(mainconnection);
            request.input('number', sql.BigInt, number);
            request.execute('[number].[pref_get]', function(err, recordsets) {
                if (err) {
                    logger.error(err);
                }
                var spResult = recordsets[0];
                if (spResult[0] != null) {
                    callback(null, spResult[0]);
                } else {
                    callback(null, null);
                }
    
            });
    
        });
    }
    

    I have testfile testDB.js coantians following code:

    require('mocha');
    
    var chai = require('chai'),
        should = chai.should(),
        expect = chai.expect,
        assert = chai.assert,
        sinon = require('sinon'),
        proxyquire = require('proxyquire');
    
    describe('Database Layer', function() {
        var stubs, number;
    
        before(function() {
            number = 72720604;
    
            stubs = {
                '../db': {
                    getDetails: function(number, callback) {
                        var data = {
                            "general": {
                                "number": "72720604"
                                "title": "Mr  ",
                                "buildingNameNumber": null,
                                "subBuildingName": null,
                                "streetName": null,
                                "postalTown": null,
                                "county": null
                            },
                            "pref": {
                                "UseAccessibilitySite": "00000",
                                "IntroductorySource": "75"
                            }
                        };
                        callback(data);
                    },
                    '@noCallThru': false
                }
            };
    
            db = proxyquire('../db', stubs);
    
        });
    
        it('should return JSON data', function(done) {
            db.getDetails(number, function(err, data) {
                expect(err).to.be.null;
                expect(data).to.deep.equal({
                    "number": "72720604"
                });
            })
        })
    
    
    
    });
    

    I am using mocha as test runner, chai as assertion library and proxyquire for overriding external dependencies. In the module db.js, there is a function getDetails that callbacks JSON data as specified in the variable stubs in testDB.js. getDetails function is internally calling SQL database operations. In the testfile testDB.js, I am stubbing the data returned from getDetails function in the variable stubs. I am unit testing getDetails function with assertion.

    The problem is when I run the test, it is still calling the original function i.e.,trying to fetch the data from SQL database but which I don't want . For that reason, I have stubbed the data so that it doesn't perform any SQL operations. I want is to test the function getDetails with stubbed data but gives the following error:

    fuera

    Any sort of help will be appreceiated!!!

    opened by prh7 17
  • Add documentation: Only works on functions

    Add documentation: Only works on functions

    I've run into situations where I want to modify the global config object (which is basically just json). Proxyquire seems like an excellent tool for this, but after much trial and error I've come to the (correct?) conclusion that this module is only designed to work on replacing functions that are dependencies of a module, not values. It might be helpful to document proxyquire doesn't change values for other wayward developers like myself (or maybe I'm alone in wanting to do this).

    For posterity's sake, in node v0.10.x, you can modify values thusly:

    require('your-module').value = 'STUB VALUE';
    

    It looks odd, but it seems to work for me.

    opened by brycefisher 17
  • Proxyquire does not override dependencies for one module only.

    Proxyquire does not override dependencies for one module only.

    I want to test one module that makes use of the fs module. So I stubbed out fs.existsSync and everything was working nicely. That was until I got to the part where I also needed to create a stub for fs.readFileSync. Suddenly it all broke. I took me a while to realize that that's because I import another module that also uses fs.readFileSync. I had also proxyquired that dependency so I didn't expect that. What happened is that even though I had a complete mock for the module, proxyquire still loaded it.

    So my question is, is there a way to tell proxyquire to either only replace the dependency once, in the module I actually requested, or if I can keep it from trying to load the dependency at all if I have a complete mock and don't just need to stub it. @noCallThru does not work for this. It still loads the module, calls fs.readFileSync and then dies.

    bug 
    opened by TimBeyer 17
  • Can not get proxyquire to work with a require that happens in an init function

    Can not get proxyquire to work with a require that happens in an init function

    I have some code like this:

    /lib/mine.js

    const path = require('path');
    
    function init(cfg) {
      var inner = require(cfg.file);
      inner.doSomething();
    }
    
    module.exports = {init};
    

    /app.js

    const mine = require(('./lib/mine');
    // Do some stuff here
    
    const cfg = {
      file: '../otherPath/otherFile'
    };
    
    mine.init(cfg);
    

    The code is much more complicated then this, but this is close enough to show the problem.

    I am writing tests for app.js above and want to use proxyquire for the file ../otherPath/otherFile

    My test file is like this:

    app.mocha.js

    const proxyquire = require('proxyquire').noCallThru();
    
    const ofStub = {
      doSomething: function() {
        // Do something
      }
    }
    
    const app = proxyquire('./app', {
      '../otherPath/otherFile': ofStub
    });
    
    

    The rest of this file does not matter since the error happens when I try to use proxyquire on app

    I get something like the following error:

    Error: Cannot find module '../otherPath/otherFile

    The thing is that it should not have tried to load that module yet since I have not called init

    Is there a way to force proxyquire to not care if the real module was loaded using require when proxyquire is initially called and just allow the module to be overridden if and when it is loaded?

    opened by intervalia 13
  • Question: How to get proxyquire work with classes?

    Question: How to get proxyquire work with classes?

    I have a class Trader which I want to do some integration tests with. This class uses another class Bitfinex which uses a service for the rest api. I want to prevent this api to make real orders on an exchange.

    proxyquire =  require('proxyquire').callThru() #take all methods which are not mocked
    BitfinexApiStub = {}
    Trader = proxyquire(applicationDir + 'backend/bitcoin/trader.class.js', './exchanges/bitfinex.class.js': {'bitfinex-api-node': BitfinexApiStub})
    
    BitfinexApiStub.rest = ()->
      return {
        new_order: ()->
          console.log "new_order"
          return null
      }
    
    

    Class

    class Bitfinex extends Bitcoin
      constructor: (options)->
        super(options)
        if options.apiKey? && options.apiSecret?
          @.bitfinexRestApi = new BitfinexApi(options.apiKey, options.apiSecret).rest
        return
    
      order: (order, callback)->
        ...
    
    module.exports = Bitfinex
    

    Error

    TypeError: Bitfinex is not a constructor

    The error only occurs when I use proxyquire instead of require.

    Question

    1. How can I mock that specific api call in the class Bitfinex?
    2. Alternatively, how could I mock the method order of Bitfinex? Which would be also fine, but I'm getting the same error.
    opened by 360disrupt 13
  • A way to fake require.resolve function

    A way to fake require.resolve function

    To start I want to say its an excellent module. Thanks for the great work.

    Now I do use proxyquire to fake certain modules, that works great. But in my application i use the function require.resolve function to get the path of the dependency but I am not able to fake it.

    Example code:

    function getPlugin(pluginName){
        var plugin = require(pluginName);
        var pluginPath = require.resolve(pluginName); // ---> Error here
    
        return {
            api: plugin,
            path: pluginPath
        };
    }
    

    Since I use proxyquire so require works but it throws an error on line 3.

    docs/examples 
    opened by gyandeeps 13
  • proxyquire won't catch dynamic requires

    proxyquire won't catch dynamic requires

    It's as if proxyquire won't stay active to catch later requires, or it is designed like that because it can't handle those.

    I surely hope to get an explanation :)

    question 
    opened by Morriz 13
  • Windows 7 not supported

    Windows 7 not supported

    Hey, great work - this is (almost) exactly what I needed for my tests :) Unfortunately though i tend to develop on multiple platforms including windows 7. When I try to use proxyquire on windows I get the following error:

        Error: Cannot find module 'V:GitHubTestRunner
    ode_modulesproxyquireproxyquire.js'
          at Function.Module._resolveFilename (module.js:338:15)
          at Function.Module._load (module.js:280:25)
          at Module.require (module.js:362:17)
          at require (C:\Users\PHALLI~1\AppData\Local\Temp\mocha.js@0:1:211)
          at new module.exports (C:\Users\PHALLI~1\AppData\Local\Temp\mocha.js@0:2:15)
          at Context.<anonymous> (V:\GitHub\TestRunner\test\grunt\mocha.test.js:23:19)
          at Test.Runnable.run (V:\GitHub\TestRunner\node_modules\mocha\lib\runnable.js:187:15)
          at Runner.runTest (V:\GitHub\TestRunner\node_modules\mocha\lib\runner.js:307:10)
          at Runner.runTests.next (V:\GitHub\TestRunner\node_modules\mocha\lib\runner.js:353:12)
          at next (V:\GitHub\TestRunner\node_modules\mocha\lib\runner.js:235:14)
    

    from a call like this:

        var MochaTask = proxyquire.resolve('../../src/grunt/mocha.js', __dirname, {
                'mocha': mochaMock(),
                'module': new ModuleMock()
            });
    

    looks like it is munging the path separators.

    BTW, using proxyquire 0.3.2

    opened by pghalliday 13
  • Unable to get proxyquire to work with node-ipInfo

    Unable to get proxyquire to work with node-ipInfo

    Hi, recently I've added the http://ipinfo.io node js wrapper (https://github.com/IonicaBizau/node-ipinfo) to my app and no matter what i've tried, I'm not able to get proxyquire+sinon to mock its behaviour. I assume its due to it exporting a function instead of an object, I've tired global=true flag written here, but no success. Any recommendations on how to approach this? Thanks

    opened by souly1 12
  • simultaneous usage of rewire and proxyquire

    simultaneous usage of rewire and proxyquire

    As I mentioned with proxyquire it is not possible to access private variables on module level. It is only possible with rewire.

    Conversely, rewire cannot stub require itself. I.e. all modules are loaded, although they should be stubbed and are not required installed for unit tests.

    Is there possible to use both of this libraries simultaneously?

    opened by hellboy81 12
  • `createRequire` support & a way to access the mocked `require`

    `createRequire` support & a way to access the mocked `require`

    The package I want to mock uses createRequire to require, which proxyquire doesn't proxy yet. To workaround, I tried:

    proxyquire('./example', {
      module: {
        createRequire: (filename) => Object.assign((id) => require(id), {
          // ...some other stuff like `resolve`
        }),
        '@global': true,
      },
      // ... stubs I use
    });
    

    But then I found the require above can't be the mocked one. I wonder if you can support createRequire and give us a way to access the mocked require (so that we can mock createRequire to return a require with our own properties).

    Thanks!

    opened by PaperStrike 6
  • Cleanup temporal module from a cache, fixes #174

    Cleanup temporal module from a cache, fixes #174

    Resolves #174 by removing reference to a newly created module from a parent module. Both the current module and the parent modules are expected to exist by the definition of this operation.

    opened by theKashey 0
  • Warn or error when stubbing non-existent functions

    Warn or error when stubbing non-existent functions

    This is great tool for writing my tests, however I've noticed that both with and without noCallThru(), if we stub a library and write out our test cases, if the underlying module methods then change, our test cases continue to work, even though the underlying methods have changed. The running code would obviously break, but the tests seems to behave just fine.

    Would it be possible to warn or even fail when stubbing functions on require()'d modules that don't actually exist?

    opened by tstackhouse 1
  • Cannot read property 'onReady' of undefined

    Cannot read property 'onReady' of undefined

    Getting this error on Windows, when requiring proxyquire in more than 1 files

    Relatively simple reproduction here

    Basically:

    • a.js
      require('proxyquire')
      
    • b.js
      require('proxyquire')
      
    • index.js
      require('./a')
      require('./b')
      

    Only seems to be happening on Windows (10, build 1809) and Node v11.4. Update: Narrowed down further to exactly 11.4, it still works on 11.3. I'm guessing it's a Node issue, probably introduced in 11.4

    Works on Node v9.5, v10.10.

    Works also on WSL (node v11.4)

    opened by laggingreflex 1
  • Recursive noPreserveCache: deps should also be reloaded

    Recursive noPreserveCache: deps should also be reloaded

    I am using proxyquire to unit test a module. I test how the module behaves when certain environment variables are absent or invalid. A dependency of the module also relies on some relevant environment variables. For each test case, I change the env vars and call proxyquire on the module. For the module to reload the new env vars, I use var proxyquire = require('proxyquire').noPreserveCache().

    The problem: Even though the env vars of the module become reloaded, the env vars of the dependency do not seem to change after the first `proxyquire(...)' call. It looks like that the dependency becomes cached. I expected the deps to be reloaded also.

    Consider a minimal example. Here is a locally available module 'getPort':

    const port = process.env.PORT
    module.exports = () => { return port }
    

    Then, here is a module 'getHost' that depends on 'getPort':

    const getPort = require('getPort')
    const host = process.env.HOST
    module.exports = () => { return host + getPort() }
    

    Next, here is a unit test suite:

    var test = require('tape')
    var proxyquire = require('proxyquire').noPreserveCache()
    var unit
    
    test('env vars', (t) => {
      process.env.PORT = 8888
      process.env.HOST = 'localhost'
      unit = proxyquire('getHost', {})
      t.equal(unit(), 'localhost:8888')  // success
    
      process.env.PORT = 8000
      process.env.HOST = 'example.com'
      unit = proxyquire('getHost', {})
      t.equal(unit(), 'example.com:8000')
      // fails, "example.com:8888" does not equal "example:8000"
    
      t.end()
    })
    

    There seems to be an inconvenient way to hack this through. I had to use the following approach after the first proxyquire call to force also the deps to reload:

    unit = proxyquire('getHost', {
      'getPort': proxyquire('getPort', {})
    })
    

    I hope this issue brings you some insight how people are using the module, in addition to the problem.

    opened by axelpale 0
Releases(v2.0.0)
  • v2.0.0(Mar 3, 2018)

    Fixes a bug where relative paths were not properly resolved and could conflict (#190). This may break your tests if they relied on buggy behavior.

    Source code(tar.gz)
    Source code(zip)
Owner
Thorsten Lorenz
Open sourcerer with focus on TypeScript/JavaScript, Rust and Flutter/Dart. Thanks for your support! 🙏 ❤️
Thorsten Lorenz
BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.

chai Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework. For more in

Chai.js Assertion Library 7.8k Dec 30, 2022
NodeJS library without any external dependencies to check if free HTTP/SOCKS4/SOCKS5 proxies are working/up

free-proxy_checker NodeJS library WITHOUT any external dependencies to: download free proxies; check if free HTTP/SOCKS4/SOCKS5 proxies are working/up

antoine vastel 15 Nov 6, 2022
A Unique Food order landing page web application called 'HOMELY' where you can select available meals and add them to cart then order them.

End Result Click the link : https://foodapp-by-eniola.netlify.com Getting Started with Create React App This project was bootstrapped with Create Reac

Eniola Odunmbaku 26 Dec 31, 2022
During work. Second team project created during CodersCamp 2021/2022 by a 6-person team.

BoardMap Status: Work in progress. Work on the project started on 10-01-2021. Our Crew Mentor: Piotr Rynio Agnieszka Przybyłowska Patryk Święcicki Rad

Piotr Rynio 3 Mar 21, 2022
A testing focused Remix Stack, that integrates E2E & Unit testing with Playwright, Vitest, MSW and Testing Library. Driven by Prisma ORM. Deploys to Fly.io

Live Demo · Twitter A testing focused Remix Stack, that integrates E2E & Unit testing with Playwright, Vitest, MSW and Testing Library. Driven by Pris

Remix Stacks 18 Oct 31, 2022
Minimal, type-safe REST client using JS proxies

Minimal, type-safe REST client using JS proxies.

Johann Schopplich 124 Dec 16, 2022
JavaScript enums using proxies.

enum-xyz JavaScript enums using proxies. Based on this tweet Install $ npm install enum-xyz --save Usage Strings import Enum from 'enum-xyz' const {

Chase Fleming 38 Oct 22, 2022
🚀 A Node.js server that automaticaly finds and checks proxies for you.

Proxi A Node.js app that automaticaly finds and checks proxies for you and shows them on a dashboard. Install & Setup ## Download git clone https://gi

Jareer Abdullah 8 Jul 7, 2022
LoopBack makes it easy to build modern API applications that require complex integrations.

LoopBack makes it easy to build modern applications that require complex integrations. Fast, small, powerful, extensible core Generate real APIs with

StrongLoop and IBM API Connect 4.4k Jan 6, 2023
browser-side require() the node.js way

browserify require('modules') in the browser Use a node-style require() to organize your browser code and load modules installed by npm. browserify wi

null 14.3k Jan 2, 2023
browser-side require() the node.js way

browserify require('modules') in the browser Use a node-style require() to organize your browser code and load modules installed by npm. browserify wi

null 14.3k Dec 31, 2022
LoopBack makes it easy to build modern API applications that require complex integrations.

LoopBack makes it easy to build modern applications that require complex integrations. Fast, small, powerful, extensible core Generate real APIs with

StrongLoop and IBM API Connect 4.4k Jan 4, 2023
browser-side require() the node.js way

browserify require('modules') in the browser Use a node-style require() to organize your browser code and load modules installed by npm. browserify wi

null 14.3k Dec 29, 2022
A demo of using the new require.context syntax in Expo with Metro bundler

Metro Context Modules Demo This is a demo of using the experimental 'Context Module' (require.context) feature in Metro bundler. Setup metro.config.js

Evan Bacon 17 Nov 19, 2022
Shikhar 4 Oct 9, 2022
Talk to anyone connected to your network, be it LAN or your hotspot. Doesn't require internet.

Apophis CLI to talk to anyone connected to your network, be it LAN or your hotspot. Doesn't require internet. Installation Make sure you have NodeJS (

Saurav Pal 3 Oct 16, 2022
🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Testing Library 17.3k Jan 4, 2023
🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Testing Library 17.3k Jan 4, 2023
Javascript-testing-practical-approach-2021-course-v3 - Javascript Testing, a Practical Approach (v3)

Javascript Testing, a Practical Approach Description This is the reference repository with all the contents and the examples of the "Javascript Testin

Stefano Magni 2 Nov 14, 2022
Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

?? Playwright Documentation | API reference Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit w

Microsoft 46.3k Jan 9, 2023