我使用自定義提供在我app.js進行後臺呼叫,然後在控制器剛剛注入該提供商並獲得承諾的結果(我做這個,因爲不是調用getLoggedUser在每個控制器我剛開始從供應商的結果),並反而讓例如10個電話我會在供應商只有一個)。但是我無法測試這個提供者$ get方法,並且測試失敗,因爲後端調用從未做過。
我得到錯誤:
Error: Unexpected request: GET https://localhost:8443/user/current
app.js
angular.module('app', [
...
])
.config(config)
.run(run)
.controller('MainCtrl', MainCtrl)
.value('version', '1.1.0')
.provider('userProvider', function(){
this.$get = ['AuthenticationService',
function(AuthenticationService) {
return AuthenticationService.getLoggedUser();
}];
});
TEST
/* jshint undef:false*/
(function() {
'use strict';
describe('ListingController', function() {
var listingController, rootScope, scope, q, mockAuthenticationService, $httpBackend, service;
var provider = {};
var mockCurrentUser = {
id: 1782,
name: "One, Coordinator",
roleId: [
3, 10
],
eauthId: "coodinator1"
};
beforeEach(module('app'));
beforeEach(module('listing'));
beforeEach(function() {
module(function (userProviderProvider) {
provider = userProviderProvider;
});
});
beforeEach(inject(function($rootScope, $controller, $q, _$httpBackend_, _AuthenticationService_, userProvider, $injector) {
rootScope = $rootScope;
scope = rootScope.$new();
$httpBackend = _$httpBackend_;
q = $q;
mockAuthenticationService = _AuthenticationService_;
// provider = userProvider;
service = $injector.invoke(provider.$get);
rootScope.$digest();
listingController = $controller('ListingController', {
$scope : scope,
mockAuthenticationService : _AuthenticationService_
});
}));
describe('getLogged user and init',function(){
it("should call getLogged function", function() {
listingController.getLoggedUser();
rootScope.$digest();
expect(service).toHaveBeenCalled();
});
});
});
})();
控制器
function getLoggedUser() {
userProvider.then(function (data){
// Here I am getting result from back end call from provider which is good
});
如果我做的提供商是這樣的:
this.$get = function (AuthenticationService) {
return {
loggedUser : function() {
return AuthenticationService.getLoggedUser();
}
}
}
然後我可以讓這樣的測試:
spyOn(provider , 'loggedUser').and.callFake(function() {
var deferred = q.defer();
deferred.resolve(mockCurrentUser);
return deferred.promise;
});
,這將工作測試將通過,但這種方法在每一個controlle當我用戶userProvider.loggedUser(),然後它會讓更多的後端調用,並與上述一個只有一次後端的通話將被製成。
更新傑蘭
如果我不喜歡你的建議從其他服務的附加呼叫正在盡一切時間......不只是一個像我有沒有函數中調用服務,並在方法調用getLoggedUser。
.provider('userProvider', function(){
return {
$get: function(AuthenticationService) {
return new userService(AuthenticationService);
}
}
});
服務
function userService(AuthenticationService) {
this.getLoggedUser = function() {
return AuthenticationService.getLoggedUser();
}
}
定義$ httpBackend –
@CeylanMumunKocabaş預期的URL請求我給它添加功能: 它( 「應該叫getLogged功能」 功能(){ listingController.getLoggedUser(); $ httpBackend.expectGET(的 'https://本地主機:8443 /用戶/電流').respond(200); $ httpBackend.flush(); }); 但是同樣的錯誤... – Bukic
'$ httpBackend.when('GET','localhost:8443/user/current')。respond(200); $ httpBackend.expect('GET','localhost:8443/user/current');' –