I wanted to create a unit test case for the following controller function.
$scope.login = function(){
$scope.login.wrong = false;
$scope.login.errorMsg = '';
var loginPromise = $http.post('backend/login', $scope.credentials);
$scope.login.working = true;
loginService.loginUser(loginPromise);
loginPromise.error(function(data, status, headers, config){
$scope.login.wrong = true;
$scope.login.errorMsg = data.errDesc;
});
loginPromise.finally(function(){
$scope.login.working = false;
if(loginService.isLogged && !$scope.login.wrong)
{
$scope.loggedInSuccessfully = true;
}
});
};
This is the service
angular.module('loginService', [])
.provider('loginService', function () {
var userToken = localStorage.getItem('userToken'),
errorState = 'app.error',
loginState = 'app.login',
logoutState = 'app.login';
this.$get = function ($rootScope, $http, $q, $state) {
var setHeaders = function (token) {
if (!token) {
delete $http.defaults.headers.common['authToken'];
return;
}
$http.defaults.headers.common['authToken'] = token.toString();
};
var setToken = function (token) {
if (!token) {
localStorage.removeItem('userToken');
} else {
localStorage.setItem('userToken', token);
}
setHeaders(token);
};
var setOrgId = function( orgId ){
if(!orgId){
localStorage.removeItem('userOrgId');
}
else{
localStorage.setItem('userOrgId', orgId);
}
setHeaderOrgId(orgId);
};
var setHeaderOrgId = function( orgId ){
if(!orgId){
delete $http.defaults.headers.common['orgId'];
return;
}
$http.defaults.headers.common['orgId'] = orgId.toString();
}
var getLoginData = function () {
if (userToken) {
setHeaders(userToken);
} else {
wrappedService.userRole = userRoles.public;
wrappedService.isLogged = false;
wrappedService.doneLoading = true;
}
};
var wrappedService = {
loginHandler: function (user, status, headers, config) {
setToken(user.authToken);
setOrgId(user.organizationId);
angular.extend(wrappedService.user, user);
wrappedService.isLogged = true;
wrappedService.userRole = userRoles[user.userType];
localStorage.setItem("anu-user",user);
return user;
},
loginUser: function (httpPromise) {
httpPromise.success(this.loginHandler);
},
/**
* Public properties
*/
userRole: null,
user: {},
isLogged: null,
pendingStateChange: null,
doneLoading: null
};
getLoginData();
managePermissions();
return wrappedService;
};
});
Can anyone please help me to write the test cases.I want to check following test cases - Check the variable working after the loginMe function is trigger. - Check that the loginService.loginUser() is been called when the loginMe function is trigger. - Mock a possible errorMsg from the Api to check that is been correctly displayed. - Check that Login button is enabled if an error message is displayed.
Aucun commentaire:
Enregistrer un commentaire