Angular 带有父变量的单元测试观察器

Angular unit testing watcher with parent variable

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();
        });
    });
});

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

似乎我能够通过提供父控制器将 $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();
        });
    });
});