【问题标题】:Unit testing scope function单元测试范围函数
【发布时间】:2015-06-08 16:11:13
【问题描述】:

我似乎不知道如何正确地对该函数进行单元测试。不管$scope.registerFail 等于true。我很确定这是因为服务调用是异步调用的,但我不确定如何处理。

这是我的单元测试

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 + '.';
            });
        });
    }
};

【问题讨论】:

  • 从我的阅读看来,我需要模拟服务调用,而不是实际执行。
  • 没错。您必须模拟它以返回一个承诺对象,而不是实际运行该服务。当您对一段代码进行单元测试时,应模拟所有外部依赖项。
  • 你能给我举个例子吗?
  • 在评论中看起来很难看,但类似于:- var deferred = $q.defer(); deferred.resolve(); spyOn(serverAuthenticationService, 'registerUser').and.returnValue(deferred.promise);
  • 如果成功,我看不到您如何使用服务返回的响应。

标签: angularjs unit-testing jasmine karma-jasmine


【解决方案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 答案以获得详细解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多