Skip to content

Instantly share code, notes, and snippets.

@klipstein
Last active August 29, 2015 14:19
Show Gist options
  • Save klipstein/58eb43b717ae5f211e2a to your computer and use it in GitHub Desktop.
Save klipstein/58eb43b717ae5f211e2a to your computer and use it in GitHub Desktop.
Dependency injection idea
function createFactory() {
var args = [].slice.call(arguments);
var createFunc = args.pop();
return function() {
if (arguments.length > 0) {
return createFunc.apply(null, arguments);
} else {
return createFunc.apply(null, args);
}
};
}
var depA = {my: 'depA'};
var depB = {my: 'depB'};
var module = {
create: createFactory(depA, depB, function(depA, depB) {
return {
key: 'value',
depA: depA
};
})
};
// in your code
var instanceWithoutDeps = module.create();
// in test
var testDepA = {test: 'depA'};
var testDepB = {test: 'depB'};
var instanceWithDeps = module.create(testDepA, testDepB);
@basecode
Copy link

The approach follows the general idea that dependencies are implicitly set in production and explicitly set in testing environment, right? Does this approach give any other benefit I don't see right now?

Fact is that your Module

  • knows about the dependencies
  • requires the dependencies

Otherwise it couldn't call createFactory correctly in production environment. As a consequence as soon as your test-file requires the Module it automatically requires the dependencies implicitly also. Not the mocks but the original ones! That might be a problem if one of the dependencies needs DOM but your testing env doesn't support DOM for example.

@klipstein
Copy link
Author

Idea came from delivering a module that contains all the default dependencies. Normally you have the dependencies outside and you have to care about collecting those in the default case, when you want to use it somewhere else. Maybe it is a good idea for the bootstrap/factory code, where you assemble your dependencies.

About the DOM problem: my assumption is that all dependencies are wrapped in a function so that a require-call would not hit the underlying service.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment