I am a newbie to unit-testing and I am trying to write tests for my loginController:
function loginController($scope, $state, authService) {
$scope.loginData = {
userName: "",
password: ""
};
$scope.message = "";
$scope.login = function () {
authService.login($scope.loginData).then(
function (response) {},
function (err) {
$scope.message = err.error_description;
});
};
//-----Load----------------------------------------
if (authService.authentication.isAuth) {
if ($scope.$stateChangeStart != null && $scope.$stateChangeStart.length > 0) {
//$scope.message = "testing2";
$state.transitionTo($scope.$stateChangeStart[$scope.$stateChangeStart.length - 1].toState, $scope.$stateChangeStart[$scope.$stateChangeStart.length - 1].toParams);
} else {
// $scope.message = "testing";
$state.transitionTo('home');
}
}
}
})();
I am trying to test the load code if user is login redirect to the last know state. I am getting a fail on the last expect($state.transitionTo).toHaveBeenCalledWith($scope.$stateChangeStart[$scope.$stateChangeStart.length - 2].toState, $scope.$stateChangeStart[$scope.$stateChangeStart.length - 2].toParams);.
Which it doesn't make sense to me. When i uncomment expect($state.transitionTo).toHaveBeenCalledWith('home'); and comment out the last expect($state.transitionTo).toHaveBeenCalledWith($scope.$stateChangeStart[$scope.$stateChangeStart.length - 2].toState, $scope.$stateChangeStart[$scope.$stateChangeStart.length - 2].toParams); then the test passed. Any idea why?
Here is my test:
it('should redirect to last state when login in', function () {
setAuthentication();
spyOn($state, 'transitionTo').andCallThrough();
var controller = createController();
$httpBackend.flush();
expect($authService.authentication.isAuth).toBe(true);
expect($scope.$stateChangeStart).not.toBe(null);
expect($scope.$stateChangeStart.length > 0).toBeTruthy();
//expect($state.transitionTo).toHaveBeenCalledWith('home');
expect($state.transitionTo).toHaveBeenCalledWith($scope.$stateChangeStart[$scope.$stateChangeStart.length - 1].toState, $scope.$stateChangeStart[$scope.$stateChangeStart.length - 1].toParams);
});