Angular Testing: Spy a function that was executed on the initialize of a controller

后端 未结 1 1931
长情又很酷
长情又很酷 2021-02-20 04:10

I\'ve been trying to spy a function that was executed on the initialize of a controller, but the test always failed. I\'ve been trying execute $scope.$digest() and

1条回答
  •  隐瞒了意图╮
    2021-02-20 04:46

    Your test is failing because spy gets overridden by real function when controller initializes. One way to avoid this is monkey-patching $scope object with custom setter for requestAuthorization property, that could create spy when controller is trying to assign value to this property:

        beforeEach(inject(function($controller, _$rootScope_, _$injector_, _$stateParams_) {
            $rootScope = _$rootScope_;
            $scope = $rootScope.$new();
            var reqAuthSpy;
            Object.defineProperty($scope, 'requestAuthorization', {
                get: function() {return reqAuthSpy;},
                set: function(fn) {
                 reqAuthSpy = jasmine.createSpy('reqAuthSpy');
                }
            });
            $stateParams = _$stateParams_;
            $stateParams.requestAuthorization = true;
    
    
            AppCtrl = $controller('AppCtrl',{
                $scope: $scope,
                $stateParams : $stateParams
            });
    
        }));
    

    0 讨论(0)
提交回复
热议问题