Search code examples
angularjsunit-testingjasmineangular-mock

What is the difference between calling _$controller_ instead of _$injector_.get('$controller')?


beforeEach(inject(function (_$controller_, _$injector_) {
  ctrl = _$controller_(...) // 1
  ctrl = _$injector_.get('$controller')(...) // 2
}));

What are the differences and which way is preferred?


Solution

  • Declaring _$controller_ in the parameters of the function passed to inject() makes the framework inject the $controller service in the function.

    Calling $injector.get('$controller') explicitly asks the $controller service to the framework.

    So it's basically the old "dependency injection vs. factory" debate. Should the framework provide the dependency to the test, or should the test ask it dependency to the framework?

    The first one is definitely preferrable in production code: it makes your code testable, and is the way you're supposed to use the framework.

    In tests, there is no significant difference, although I prefer the first one too.