我正在尝试测试我是否收到并存储了API发送的令牌。
我的控制器正在向服务器询问凭据是否正常:
var app = angular.module('App', ['ngMaterial', 'ngMessages'])
app.controller('Ctrl', ['$rootScope', '$scope','$http','$timeout','$mdDialog','Global', 'projects', 'screens', 'users', 'licenses', function($rootScope, $scope, $http, $timeout, $mdDialog,Global, projects, screens, users, licenses) {
//Ask for connexion to the server
$rootScope.Connect = () => { // === $rootScope.Connect = function() { ... }
//Set params to request
var request = Global.url_api+'action=Connection&username='+$scope.username+
'&password='+$scope.pwd+
'&project='+$rootScope.project;
//Ask to the server if credentials is correct
$http.get(request)
.then((response) => {
if(response.status == 200){ //Status 200 : Everything OK
var jwt_token = response.data.jwt;
localStorage.setItem('tokenAPI',jwt_token); //Set the token sent by server in localStorage
Global.update_key(jwt_token); //Update global.url_api
if(response.data.admin) $scope.admin_connected = true;
$scope.credentials = true; //Set visible the tab
$rootScope.getProjectData(); //Get projects data from DB
}
})
}
}]);
我的测试文件:
describe('MainController', ()=>{
beforeEach(()=>{module('App')});
var $controller, $scope , $rootScope ;
beforeEach(angular.mock.inject((_$controller_,_$rootScope_)=>{
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$rootScope.project = "IDRIS";
$controller = _$controller_('Ctrl',{$scope : $scope});
}))
it("Should be defined",()=>{
expect($controller).toBeDefined();
})
describe('Connection',()=>{
beforeEach(()=>{
$scope.username = "adminUsername";
$scope.pwd = "adminPassword";
$rootScope.Connect()
})
it("Should return a token if credentials are true", ()=>{
expect(localStorage.getItem('tokenAPI')).not.toBe(null);
})
})
})
我的localStorage如果总是为null。
我不知道是否必须使用$ httpBackend服务,因为实际上是我的控制器正在发出请求,显然,我无法预测服务器将为我提供什么标记。
我不知道我是不是很好。 谢谢你
答案 0 :(得分:0)
首先检查您是否确实从服务器获取了任何数据
console.log(response.data.jwt);
如果是,请考虑数据的格式。本地存储只能存储字符串。从api接收的任何JSON对象必须首先进行字符串化处理:
localStorage.setItem('tokenAPI', JSON.stringify(jwt_token));
如this帖子中所述。