Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

How to inject Angular dependencies in Jasmine unit tests

Torgeir "Tor" Helgevold
- JavaScript 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.

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');
    });

});

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter