测试我的控制器功能不会进入.then

时间:2018-01-19 17:42:54

标签: angularjs unit-testing jasmine karma-jasmine

我还是单元测试的新手,我试图在我的组件控制器上测试一个函数,它使用api调用的服务但是我注意到当我运行测试时它不会进入内部。然后请求退货。

这是我的组件'arSchoolComponent':

UserControl

这是我的服务'$ schoolsService':

var arSchoolComponent = {
templateUrl: "ar-school.component.html",
controller: arSchoolComponentCtrl,
controllerAs: 'schoolCtrl'
};

arSchoolComponentCtrl.$inject = [
    "$schoolsService",
    "$permissionService",
    "$stateParams",
    "$state",
    "$scope",
    "arAuthenticationService",
    "$mdDialog",
    "$notificationService",
    "$translate"
];

function arSchoolComponentCtrl($schoolsService,
                               $permissionService,
                               $stateParams,
                               $state,
                               $scope,
                               arAuthenticationService,
                               $mdDialog,
                               $notificationService,
                               $translate) {


// @variables
var vm = this;
vm.loading = false;
vm.selectedSchool = null;

// @methods
vm.getSchool = getSchool;

vm.$onInit = function () {
  //this is equal to getSchool(1)
  getSchool(vm.currentUser.information.staff.schools[0].schoolId);
};

/**
 * Load school data from server
 *
 * @param id
 */
function getSchool(id) {
    preloader.on();

    if (!vm.loading) {
        vm.loading = true;

        var request = $schoolsService.getSchool(id);

        request.then(function (response) {
            vm.selectedSchool = response.data;
            vm.loadCompleted = true;
        }).then(function () {
            vm.loading = false;
            preloader.off();
        });
    }
}


}

这是我的单元测试:

var arSchoolsService = [
'UtilityService',
'$q',
function($utility, $q) {

    var _this = this;

    //@variables
    _this.user = null;
    _this.baseUrl = 'api/school'; // Server base url for request
    _this.selectedSchool = null; // Selected School
    _this.schools = []; // Array of schools
    _this.validationError = false;

    var service = {
        getSchool: getSchool

    };

    return service;

    //@methods

    /**
     * Return one school
     *
     * @param schoolId
     */
    function getSchool(schoolId) {
        return $utility.sendRequest('GET', _this.baseUrl + '/' + schoolId);
    }
}

当我通过ctrl.getSchool(2)调用函数getSchool时,我监视服务方法getSchool spyOn($ schoolsService,'getSchool')。and.returnValue(deferred.promise);和期望($ schoolsService.getSchool).toHaveBeenCalledTimes(1);是正确的它显示它通过该功能,并调用schoolsService.getSchool但ctrl.selectedSchool没有更新,这意味着它没有进入.then

我知道我在这里遗漏了一些东西,可以请任何人帮忙解决这个问题。

1 个答案:

答案 0 :(得分:0)

你没有解决这个承诺,所以永远不会去#34; .then()",你需要解决它:

spyOn($schoolsService, 'getSchool').and.returnValue(deferred.promise);
ctrl.getSchool(2);
deferred.resolve({school: 'myschooldata'});

如果你想获得你在$ httpBackend中设置的数据,那么你应该添加 .and.returnValue(...),而不是 .and .callThrough()如果你这样做,你可能需要在调用getSchool()之后再次刷新http请求,即 $ httpBackend.flush()