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