Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS: unit tests gives: Unknown provider: $httpProviderProvider <- $httpProvider

In one of my unit tests I'm trying to do

beforeEach(function () {
    angular.mock.inject(function ($injector) {
        $httpBackend = $injector.get('$httpBackend');
        mockUserResource = $injector.get('User');
        $httpProvider = $injector.get('$httpProvider');  // <-- problem
        $httpProvider.interceptors.push('myInterceptor');
    });
});

(demo)

Why is it not possible to inject $httpProvider ?

The reason I'm doing this is because I don't load the file which adds all my interceptors, because I want to test them one by one!

like image 236
Jeanluca Scaljeri Avatar asked Nov 04 '13 12:11

Jeanluca Scaljeri


2 Answers

Providers are only injectable in the config phase, angular.config.

According to this answer, you could try something like:

beforeEach(module('yourModule', function($httpProvider) {
  $httpProvider.interceptors.push('myInterceptor');
}));

beforeEach(function() {
  angular.mock.inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');
    mockUserResource = $injector.get('User');
  });
});

For more information on how dependency injection works, this is a great article (not written by the AngularJS team)

like image 103
M.K. Safi Avatar answered Oct 19 '22 02:10

M.K. Safi


The name Provider is automatically added by angular. So, you should just inject $http.

$httpProvider = $injector.get('$http'); 

here is a working fork of your fiddle.

like image 1
Davin Tryon Avatar answered Oct 19 '22 01:10

Davin Tryon