2016-07-05 124 views
1

我想弄清楚爲什麼我的測試試圖爲我的服務找到提供者。爲什麼需要測試服務提供商(未知提供商)?

beforeEach(function() { 
    module('loggingModule', inject(function ($q, _loggingService_) { 
     var deferred = $q.defer(); 
     var loggingService = _loggingService_; 
     deferred.resolve('somevalue'); // always resolved, you can do it from your spec 

     // jasmine 2.0 
     spyOn(loggingService, 'removeAndGetNext').and.returnValue(deferred.promise); 
    })); 
}); 

loggingServiceloggingModule的一部分,作爲服務註冊了。

打電話給我測試失敗,

未知提供商:loggingServiceProvider < - loggingService

如果我注入我的服務與構造函數注入它的工作原理控制器。

爲什麼測試需要提供商?

回答

1

首先建立與beforeEach(module('loggingModule'))角模塊比incject一些依賴beforeEach(inject(function() {})),這樣的:

angular.module('loggingModule', []) 
 
    .service('loggingService', function($q) { 
 
    this.methodUnderTest = function(attr) { 
 
     return this.removeAndGetNext(attr) 
 
    } 
 
    this.removeAndGetNext = function() { 
 
     // return $q.resolve('foo') 
 
    } 
 
    }) 
 

 
describe('Module `loggingModule`', function() { 
 
    var loggingService 
 
    var promise 
 
    var $rootScope 
 

 
    beforeEach(module('loggingModule')) 
 

 
    beforeEach(inject(function($q, _loggingService_, _$rootScope_) { 
 
    loggingService = _loggingService_ 
 
    $rootScope = _$rootScope_ 
 
    promise = $q.defer() 
 
    spyOn(loggingService, 'removeAndGetNext').and.returnValue(promise.promise) 
 
    })) 
 

 
    it('.methodUnderTest() calls .removeAndGetNext()', function(done) { 
 
    var mockArgument = 'some arguments' 
 
    var mockResponse = 'some resolved value' 
 

 
    loggingService.methodUnderTest(mockArgument).then(function(r) { 
 
     expect(r).toBe(mockResponse) 
 
     expect(loggingService.removeAndGetNext).toHaveBeenCalledWith(mockArgument) 
 
     done() 
 
    }) 
 
    
 
    promise.resolve(mockResponse) 
 
    $rootScope.$apply() 
 
    }); 
 
})
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" /> 
 
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>