Unit testing scope function

703 views Asked by At

I can't seem to figure out how to properly unit test this function. Nomatter what $scope.registerFail is equal to true. I am pretty sure this is because the service call is getting called asynchronously but I'm unsure how to handle that.

Heres is my unit test

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

And this is my function:

$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

There are 1 answers

0
Abhishek Jain On

Try this:-

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 for a similar SO answer for detailed explanation.