我的服务是:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$state', '$cookies', '$base64', function($http, $q, $rootScope, $state, $cookies, $base64) {
var user;
user = {};
this.logout = function() {
user = {};
delete $cookies.userAccessKey;
return $state.transitionTo('login');
};
}
]);
我想编写单元测试以确保$cookies.userAccessKey
已删除。我怎样才能做到这一点?在我这样做的同时,我如何确保将user
设置为空?
答案 0 :(得分:1)
要检查用户是否为空,只需添加公共getter或checker:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$state', '$cookies', '$base64', function($http, $q, $rootScope, $state, $cookies, $base64) {
var user;
this.user = {}; // or a method this.isLoggedIn() for more security
this.logout = function() {
this.user = {};
delete $cookies.userAccessKey;
return $state.transitionTo('login');
};
}
]);
然后,在你的测试中:
describe('logout', function(){
beforeEach(function(){
userService.login(); //relog before each test
});
it('should remove the userAccessKey from cookie', function() {
userService.logout();
inject(function($cookies) {
expect(cookies.userAccessKey).toBeUndefined();
});
});
it('should reset user object', function() {
userService.logout();
expect(userService.user).toEqual({});
});
});
});