角度单元测试观察者与父变量

时间:2016-04-14 08:20:49

标签: javascript angularjs unit-testing jasmine angularjs-watch

如果观察者观看$ 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();
        });
    });
});

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

1 个答案:

答案 0 :(得分: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();
        });
    });
});