Hacker News new | past | comments | ask | show | jobs | submit login

Injected dependencies are more easily stubbed/mocked for testing purposes.



That is not actually all that true in JS, or generally any languages where without static types or classes that aren't duck-typed objects themselves.

Its true in C++/Java/C#, but less so in JS, Ruby, etc. If you can change what a dependency refers to without using injection, as you generally can in the fact namuc languages, injection is less useful.


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: