AngularJS Unit Testing - Various patterns for injecting dependencies

北城余情 提交于 2019-12-04 06:52:11

I've gleaned that Angular core services/providers should be injected with the underscore pattern where as other 3rd party dependencies or my own dependencies should be done using the $injector.get() pattern

You can use either. The underscore pattern is simply a convenience method to avoid conflicts with local variables of the same name. Consider the following

var $rootScope, myService, http; // these are local variables

beforeEach(inject(function(_$rootScope_, _myService_, $http) {
    $rootScope = _$rootScope_; // underscores to avoid variable name conflict
    myService = _myService_; // same here with your custom service
    http = $http; // local variable is named differently to service
}));

If I can just add services to the inject callback like this code does with $location, that seems like a simpler way of referencing dependencies. Why should I not do this?

You should :)


Also, what is the point of 'security/loginModal.tpl.html' in beforeEach(angular.mock.module('security.service', 'security/loginModal.tpl.html'));?

As far as I know, unless you have an actual module with that name, eg

angular.module('security/loginModal.tpl.html', [])

this will fail. angular.mock.module should only be passed module names, instances or anonymous initialisation functions.


how do I mock 'security/loginModal.tpl.html'

Ideally, you shouldn't. Unit tests should test the API of your code... points of interaction, typically defined by publically accessible methods and properties on your objects.

If you're just trying to prevent Karma from attempting to load templates over HTTP (usually from directive tests), you can use a template pre-processor like karma-ng-html2js-preprocessor


Lastly, what can I and can't inject in nested describe and it blocks? Is it safe to assume I can't retro-inject mocked services to the module I'm testing. So then what can I inject and what are the use cases?

You can run angular.mock.inject just about anywhere (typically beforeEach and it). Mocked services should only be configured in a module or anonymous module initialisation function (as in your example with $provide and $window) and typically after your own module(s) (ie "security.service") in order to override the real services by replacing them in the injector. Once you've run inject(), you cannot retro-actively replace a service with a mock.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!