AngularJS Jasmine 编写测试代码

AngularJS Jasmine writing testing code

我是单元测试的新手,我正在尝试为我的 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');
            }
        }
    }
})();

如果用户登录重定向到最后知道的状态,我正在尝试测试加载代码。我在最后一个 expect($state.transitionTo).toHaveBeenCalledWith($scope.$stateChangeStart[$scope.$stateChangeStart.length - 2].toState, $scope.$stateChangeStart[$scope.$stateChangeStart.length - 2].toParams);.

上失败了

这对我来说没有意义。当我取消注释 expect($state.transitionTo).toHaveBeenCalledWith('home'); 并注释掉最后一个 expect($state.transitionTo).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);
});