我试图弄清楚为什么我的测试试图为我的服务找到提供者。
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);
}));
});
loggingService是loggingModule的一部分,并在那里注册为服务。
致电测试失败
未知提供者:loggingServiceProvider
如果我通过构造函数注入将服务注入控制器,那么它将起作用。
为什么测试需要提供者?
最佳答案
首先使用beforeEach(module('loggingModule'))
设置Angular模块,然后注入一些依赖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>