Javascript AngularJS Jasmine编写测试代码
我是单元测试的新手,我正在尝试为我的loginController编写测试:Javascript AngularJS Jasmine编写测试代码,javascript,angularjs,jasmine,Javascript,Angularjs,Jasmine,我是单元测试的新手,我正在尝试为我的loginController编写测试: function loginController($scope, $state, authService) { $scope.loginData = { userName: "", password: "" }; $scope.message = ""; $scope.login = function () { authService.l
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');
}
}
}
})();
我试图测试加载代码,如果用户登录重定向到最后知道的状态。我在上一次expect($state.transitiono).toHaveBeenCalledWith($scope.$stateChangeStart[$scope.$stateChangeStart.length-2].toState,$scope.$stateChangeStart[$scope.$stateChangeStart.length-2].toParams)中失败代码>
这对我来说毫无意义。当我取消注释时,期望($state.transitiono).tohavencalledwith('home')编码>并注释掉最后一个expect($state.transitiono).toHaveBeenCalledWith($scope.$stateChangeStart[$scope.$stateChangeStart.length-2].toState,$scope.$stateChangeStart[$scope.$stateChangeStart.length-2].toParams)代码>然后测试通过。知道为什么吗
这是我的测试:
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);
});
我必须刷新对authService的更改:
此测试现在通过:
it('should redirect to last state when login in', function () {
setAuthentication();
$httpBackend.flush();
spyOn($state, 'transitionTo').andCallThrough();
var controller = createController();
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);
});