It's not so much about duck typing, as it is about private/public variables and how they relate to a module's interface. `require`d modules are essentially private in Javascript. Consider the following:
// foo.js
var request = require('request');
module.exports = function (url) {
request.get(url, function (err, body) {
// ... business logic here.
});
}
Here, if one wanted to test the actual business logic (without implicitly testing the request module as well), one would have to refactor the code such that the callback is somehow exposed to the test suite. Additionally, one would not be able to run such tests in isolation (i.e. without an internet connection), and the test speed would depend on network latency.
Now consider another example:
// injected.js
module.exports = function (request) {
return function (url) {
request.get(url, callback);
}
}
In this version, the request library is taken as an argument to the module and thus can have a mocked version injected for testing purposes.
Now consider another example:
In this version, the request library is taken as an argument to the module and thus can have a mocked version injected for testing purposes.