【发布时间】:2015-11-17 07:38:56
【问题描述】:
我有两个角色:一个是管理员,另一个是普通用户。管理员可以导航到项目详细信息页面,而普通用户不能。因此,我在用户登录时将用户的角色存储在“全局”cookie 中。我从 cookieStore 获取他们的角色,以检查哪个可以导航到项目详细信息页面。这个功能很好用。但是,我不知道如何在 checkUserRole 函数中为 $cookieStore 编写测试:
angular.module('config', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider)
{
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('login',
{
url: '/login',
templateUrl: 'login-page.html',
controller: 'LoginController'
})
.state('index',
{
url: '/index',
templateUrl: 'bridge.html'
})
.state('item-detail',
{
url: '/index/item-detail/:Name',
templateUrl: 'item-detail.html',
controller: 'myCtrl',
resolve:
{
checkUserRole: function($cookieStore)
{
if($cookieStore.get('globals').currentUser.userRole === 'user')
{
return state.go('index');
}
}
}
});
});
还有,这是我的测试用例:
describe('config', function()
{
var $scope, $state, $cookieStore, userRole;
beforeEach(function()
{
module('config', function($provide)
{
$provide.value('$cookieStore', { get: 'globals' });
});
inject(function($injector, $templateCache)
{
$scope = $injector.get('$rootScope');
$state = $injector.get('$state');
$cookieStore = $injector.get('$cookieStore');
$templateCache.put('login-page.html', '');
$templateCache.put('bridge.html', '');
$templateCache.put('item-detail.html', '');
});
});
it('home page', function()
{
$scope.$apply();
expect($state.current.name).toBe('login');
expect($state.current.templateUrl).toBe('login-page.html');
expect($state.current.controller).toBe('LoginController');
});
it('login page', function()
{
$scope.$apply(function()
{
$state.go('login');
});
expect($state.current.name).toBe('login');
expect($state.current.templateUrl).toBe('login-page.html');
expect($state.current.controller).toBe('LoginController');
});
it('items page', function()
{
$scope.$apply(function()
{
$state.go('index');
});
expect($state.current.name).toBe('index');
expect($state.current.templateUrl).toBe('bridge.html');
});
it('item-detail page', function()
{
spyOn($cookieStore, 'get').and.callFake(function()
{
return 'user';
});
expect($cookieStore.get('globals')).toBe('user');
$scope.$apply(function()
{
$state.go('item-detail');
});
expect($state.current.name).toBe('item-detail');
expect($state.current.templateUrl).toBe('item-detail.html');
expect($state.current.controller).toBe('myCtrl');
expect($state.href('item-detail', { Name: 'lumia-950'})).toEqual('#/index/item-detail/lumia-950');
});
});
我的问题是:如何为$cookieStore.get('globals').currentUser.userRole 编写测试?或者我如何模拟它来测试用户的角色是否是用户?。
【问题讨论】:
标签: angularjs unit-testing jasmine angular-mock