thlorenz / proxyquire

🔮 Proxies nodejs require in order to allow overriding dependencies during testing.
MIT License
2.75k stars 100 forks source link

Using stub map as module whitelist #132

Closed flamestream closed 8 years ago

flamestream commented 8 years ago

Quickly reading the documentation, I was confused by the usage of noCallThru(), thinking that it would enable me to do something as follows:

test.js

const proxyquire = require('proxyquire').noCallThru();
proxyquire('index.js', {
   module1: require('module1'),
});

index.js

require('module1'); // Module found and all chained requires loaded
require('module2'); // Module not found in whitelist and will throw an error

However, rereading more carefully, it seemed to not be the intent. Is there anything in place that will let me achieve the above easily? For unit testing, it would make sense to explicitly list what can be loaded instead.

bendrucker commented 8 years ago

Is there anything in place that will let me achieve the above easily?

No, proxyquire only overrides requires that match the stub list. noCallThru allows you to replace fs with {readFile: readFileStub} while preserving the rest of the methods.

To simulate a module being unavailable, set it's stub value to null.