0

如果 watcher 监视 $parent 范围变量,如何测试它?例如,我进入了儿童范围:

$scope.$parent.$watch('activeId', function (hotelId) {
    $scope.select(activeId);
});

目前测试的样子:

...

    beforeEach(inject(function (_$controller_, _$rootScope_) {

       $scope = _$rootScope_.$new();
       $parentScope = _$rootScope_.$new();

       $controller = _$controller_('ChildCtrl', {'$scope': $scope});
       $parentController = _$controller_('ParentCtrl', {'$scope': $parentScope});
    }));

    describe('select', function () {
        beforeEach(function () {
           spyOn($scope, 'select');
        });
        it('should call select', function () {
           $parentScope.setActiveId(1);
           $parentScope.$digest();

           expect($scope.select).toHaveBeenCalled();
        });
    });
});

但不幸的是,这个测试失败了。

4

1 回答 1

1

似乎我能够通过像这样提供父控制器将 $parent 添加到 $scope 来处理这个问题并通过测试:

describe('Controller: TestController', function () {

    beforeEach(module('App'));

    var $controller, $scope, $parentController, $parentScope;

    beforeEach(inject(function (_$controller_, _$rootScope_) {

        $scope = _$rootScope_.$new();
        $parentScope = _$rootScope_.$new();
        $scope.$parent = $parentScope;

        $parentController = _$controller_('ParentController', {'$scope': $parentScope});
        $controller = _$controller_('ChildCtrl', {'$scope': $scope});
    }));
    it('should get $parent variable', function () {
        var userId=$scope.$parent.vm.userId;
        var simId=$scope.$parent.vm.simId;
    })
       describe('select', function () {
        beforeEach(function () {
           spyOn($scope, 'select');
        });
        it('should call select', function () {
           $scope.$parent.setActiveId(1);
           $scope.$parent.$digest();

           expect($scope.select).toHaveBeenCalled();
        });
    });
});
于 2016-04-14T14:27:14.043 回答