我想知道,为什么我的测试试图为我的服务找到提供商。
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< - loggingService
如果我将我的服务注入带有构造函数注入的控制器,它就可以工作。
为什么测试需要提供者?
答案 0 :(得分:1)
首先使用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>