How to inject Angular dependencies in Jasmine unit tests

- Developer and Blogger
Published: Sun May 10 2015

Angular dependency injection is very flexible and easy to work with, but how do you inject dependencies in Jasmine tests. In the following short post I will show two common approaches

Angular dependency injection is very flexible and easy to work with, but how do you inject dependencies in Jasmine tests? In the following short post I will show two common approaches.

1) Using the injector object directly

By listing the modules to inject from you can use the injector directly from window.angular

var $injector = window.angular.injector(['app','ng']);
var greetingService = $injector.get('greetingService');

The above code lets you inject objects defined in the app and ng modules.

2) Use the inject method

Jasmine exposes an inject method that lets you inject dependencies like this:

var greetingService;

beforeEach(function(){

    module('app');

    inject(function (_$injector_) {
        greetingService = _$injector_.get('greetingService');
    });

});