0
我試圖測試我的控制器,它調用何時啓動服務返回包含用戶名的承諾。它總是失敗,我不明白爲什麼。Angularjs和茉莉花,測試諾言
模塊:
(function() {
'use strict';
angular.module('dilib', [
// Angular modules
'ngAnimate',
'ngRoute',
// Custom modules
'dilib.layout',
// 3rd Party Modules
'LocalStorageModule',
'restangular'
])
.config(function (RestangularProvider) {
RestangularProvider.setBaseUrl('http://localhost/services/webapi/');
})
.config(function (localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('dilib');
});
})();
控制器:
(function() {
'use strict';
var controllerId = 'requestAuthorizationController';
angular
.module('dilib')
.controller(controllerId, requestAuthorizationController);
requestAuthorizationController.$inject = ['requestAuthorizationService'];
function requestAuthorizationController(requestAuthorizationService) {
/* jshint validthis:true */
var vm = this;
vm.username = undefined;
activate();
function activate() {
return requestAuthorizationService.requestAuthorization().then(function (result) {
vm.username = result;
return vm.username;
});
}
}
})();
服務:
(function() {
'use strict';
var serviceId = 'requestAuthorizationService';
angular
.module('dilib')
.service(serviceId, requestAuthorizationService);
requestAuthorizationService.$inject = ['$q'];
function requestAuthorizationService($q) {
//API
var service = {
requestAuthorization: requestAuthorization,
}
return service;
/////////////////////////////////////////////////////////////////////
function requestAuthorization(user) {
var defer = $q.defer();
defer.resolve('visitor');
return defer.promise;
}
}
})();
規格:
//requestAuthorizationController Specification
'use strict';
describe('requestAuthorizationController Specification', function() {
var RestangularProvider,
localStorageServiceProvider,
controller,
requestAuthorizationServiceMock,
$rootScope,
scope;
beforeEach(function() {
angular.module('ngAnimate', []);
angular.module('ngRoute', []);
angular.module('dilib.layout', []);
//angular.module('LocalStorageModule', []);
angular.module('http-auth-interceptor', []);
//angular.module('restangular', []);
});
beforeEach(function() {
module('dilib', function(_RestangularProvider_, _localStorageServiceProvider_, $provide) {
RestangularProvider = _RestangularProvider_;
localStorageServiceProvider = _localStorageServiceProvider_;
$provide.service('requestAuthorizationService', function ($q) {
this.requestAuthorization = jasmine.createSpy('requestAuthorization').and.callFake(function(result) {
var defer = $q.defer();
defer.resolve('visitor');
return defer.promise;
});
});
});
});
beforeEach(inject());
beforeEach(inject(function ($controller, _$rootScope_, requestAuthorizationService) {
controller = $controller;
requestAuthorizationServiceMock = requestAuthorizationService;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
}));
it('Provides the authenticated user name', function() {
var vm = controller('requestAuthorizationController');
expect(vm.username).toBe('visitor');
});
});
這裏是plunker。
感謝您提前提供任何幫助!