Angular 测试:侦测在控制器初始化时执行的函数

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

我一直在尝试监视在控制器初始化时执行的函数,但测试总是失败。 我一直在尝试执行 $scope.$digest() 但它不起作用,但是在控制台中,我看到该函数已被调用。

我想不通,有人可以向我解释为什么它不起作用吗?

Codepen 示例: http://codepen.io/gpincheiraa/pen/KzZNby

控制器

function Controller($stateParams, $scope){

  $scope.requestAuthorization = requestAuthorization;

  if ($stateParams.requestAuthorization === true) {
    console.log('$stateParams.requestAuthorization');
    $scope.requestAuthorization();
  }
  function requestAuthorization() {
    console.log('requestAuthorization()');
  }
}

测试

describe('AppCtrl', function(){
     var AppCtrl, $rootScope, $scope, $stateParams;

    beforeEach(module('exampleApp'));

    beforeEach(inject(function($controller, _$rootScope_, _$injector_, _$stateParams_) {
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        $stateParams = _$stateParams_;
        $stateParams.requestAuthorization = true;


        AppCtrl = $controller('AppCtrl',{
            $scope: $scope,
            $stateParams : $stateParams
        });

        spyOn($scope, 'requestAuthorization');          
    }));

     it('$stateParams.requestAuthorization should be defined', function() {             
        expect($stateParams.requestAuthorization).toBeDefined();
    });

    it('$scope.requestAuthorization should be defined', function() {
        expect($scope.requestAuthorization).toBeDefined();
    });

    // this test is not passing.. 
    it('should call requestAuthorization', function() {
                //$scope.$digest();
        expect($scope.requestAuthorization).toHaveBeenCalled();
    });

});

你的测试失败了,因为当控制器初始化时,spy 被实际函数覆盖。避免这种情况的一种方法是使用针对 requestAuthorization 属性 的自定义 setter 猴子修补 $scope 对象,这可能会在控制器尝试为此 [=16] 赋值时创建间谍=]:

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

    }));