单元测试范围功能

时间:2015-06-08 16:11:13

标签: angularjs unit-testing jasmine karma-jasmine

我似乎无法弄清楚如何正确单元测试此功能。 Nomatter $scope.registerFail等于true。我很确定这是因为服务调用是异步调用的,但我不确定如何处理它。

Heres是我的单元测试

it('should fail', function(){
    $scope.registerForm={};
    $scope.registerForm.$valid = true;
    $scope.registerFail = true;
    $scope.register();
    expect($scope.registerFail).toEqual(false);
});

这是我的职责:

$scope.register = function () {
    var vm = this;
    if (vm.registerForm.$valid) {

        var names = vm.user.fullName.split(' '),
            first_name = names[0],
            last_name = '',
            payload;

        //Parse full name into first and last name 
        if (names.length > 1) {
            first_name = vm.user.fullName.substr(0, vm.user.fullName.length - names[names.length - 1].length - 1);
            last_name = names[names.length - 1];
        }

        payload = {
            email: vm.user.email,
            password: vm.user.password,
            password_confirmation: vm.user.password_confirmation,
            first_name: first_name,
            last_name: last_name,
            terms_and_conditions: vm.user.terms_and_conditions,
            over_13: vm.user.over_13,
            ens_weekly_updates: vm.user.ens_weekly_updates,
            referrer_id: null
        };

        serverAuthenticationService.registerUser(payload).then(function(response){
            $scope.registerFail = false;
            $modalInstance.close();
            $state.go('business-profile.details');
        }, function (reason) {
            $scope.registerFail = true;
            angular.forEach(reason.data.errors, function (error) {
              error.field = error.field.substring(0, 1).toUpperCase() + error.field.substring(1);
              $scope.registerErrors = error.field + ' ' + error.info + '.';
            });
        });
    }
};

1 个答案:

答案 0 :(得分:1)

试试这个: -

it('should fail', function(){
    spyOn(serverAuthenticationService, 'registerUser').and.returnValue($q.when(false));
    $scope.registerForm={};
    $scope.registerForm.$valid = true;
    $scope.registerFail = true;
    $scope.register();
    $scope.$apply(); // Forces $q.promise then callbacks to be called
    expect($scope.registerFail).toEqual(false);
});

Read here获得详细解释的类似SO答案。