jjzjj

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

coder 2024-05-14 原文

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

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

代码笔示例: http://codepen.io/gpincheiraa/pen/KzZNby

Controller

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

});

最佳答案

你的测试失败了,因为当 Controller 初始化时,spy 被真正的函数覆盖了。避免这种情况的一种方法是使用 requestAuthorization 属性的自定义 setter 对 $scope 对象进行猴子修补,这可能会在 Controller 尝试为该属性赋值时创建 spy :

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

    }));

关于javascript - Angular Testing : Spy a function that was executed on the initialize of a controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36503406/

有关javascript - Angular Testing : Spy a function that was executed on the initialize of a controller的更多相关文章

随机推荐