【发布时间】:2015-03-15 17:16:51
【问题描述】:
我的应用中有以下控制器:
angular.module('newradarApp').controller('ProfileController', ['$scope', '$log', '$auth', 'userRestService', function ($scope, $log, $auth, userRestService) {
/**
* loading ui toggle ativator
*/
$scope.userLoaded = false;
/**
* @returns {*} Checks (In combination with satellizer) the contextual authentication state
*/
$scope.userIsLoggedIn = function () {
return $auth.isAuthenticated();
};
//$scope.welcomeMsg = 'Welkom, ';
/**
* Holds the instance of the user's service
*/
var userServiceInstance = userRestService.obtainPersonalInformation().then(function (userData) {
$log.debug('::ReST-obtainPersonalInformation Got user data:', JSON.stringify(userData));
$scope.userName = userData.firstName;
$scope.fullName = userData.firstName + ' ' + userData.lastName;
$scope.picture = encodeURI(userData.profilePicture);
$scope.userLoaded = true;
});
}]);
我想用 Jasmine 测试这个功能,我用这种方式尝试了这个测试:
'use strict';
describe('Controller: ProfileController', function () {
// load the controller's module
beforeEach(module('newradarApp'));
var ProfileController, scope, mockUserrest, def;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $q) {
mockUserrest = {
obtainPersonalInformation: function () {
def = $q.defer();
return def.promise;
}
};
spyOn(mockUserrest, 'obtainPersonalInformation').andCallThrough();
scope = $rootScope.$new();
ProfileController = $controller('ProfileController', {
$scope: scope
});
}));
it('should assign data to scope', function () {
def.resolve(userdata);
scope.$digest();
expect(mockUserrest.obtainPersonalInformation).toHaveBeenCalled();
expect(scope.userName).toBe(userdata);
});
});
然后我尝试使用其他方式模拟服务的其他测试:
'use strict';
describe('Controller: ProfileController', function () {
// load the controller's module
beforeEach(angular.mock.module('newradarApp'));
var controller, scope, rootScope, mockUserrest, def;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $q) {
rootScope = $rootScope;
scope = $rootScope.$new();
controller = $controller;
mockUserrest = {
obtainPersonalInformation: function () {
def = $q.defer();
def.resolve(userdata);
return def.promise;
}
}
}));
it('should assign data to scope', function () {
controller("ProfileController", {$scope: scope, userRestService: mockUserrest});
scope.$digest();
expect(scope.username).toBe(userdata)
});
});
每个都没有通过,所以请提示我做错了什么?
【问题讨论】:
标签: angularjs unit-testing controller mocking