2015-06-11 45 views
1

當我嘗試spyOn一個$範圍。$手錶的監聽功能,就像是從來不叫spyOnspyOn監聽監控功能不能正常工作

http://jsfiddle.net/b8LoLwLb/1/

我控制器

angular.module('angularApp') 
    .controller('MainCtrl', function ($scope) { 
     $scope.name = ''; 

     this.changeName = function() { 
      console.log('the name has change to ' + $scope.name); 
     }; 

     $scope.$watch('name', this.changeName); 
    }); 

我測試

describe('Controller: MainCtrl', function() { 

    // load the controller's module 
    beforeEach(module('angularApp')); 

    var MainCtrl, 
     scope; 

    // Initialize the controller and a mock scope 
    beforeEach(inject(function ($controller, $rootScope) { 
     scope = $rootScope.$new(); 
     MainCtrl = $controller('MainCtrl', { 
      $scope: scope 
     }); 
    })); 

    it('should check if watcher was triggered', function() { 
     // Spy the listener funtion 
     spyOn(MainCtrl, 'changeName'); 

     // Change the watched property 
     scope.name = 'facu'; 

     // Digest to trigger the watcher. 
     scope.$digest(); 

     // Expect the function to have been called 
     expect(MainCtrl.changeName).toHaveBeenCalled(); 
    }); 
}); 

問題是,代替窺探功能,測試前執行它並打印控制檯日誌。

我採用了棱角分明1.4

+0

檢查js小提琴時,監視器的監聽器功能在控制器實例化時不運行。 –

回答

1

這是正常現象,它無關茉莉或角而是由酒店舉行的函數引用做。當您在控制器實例上做$scope.$watch('name', this.changeName)時,設置爲收看this.changeName那時的)保存的功能參考。即使您監視控制器實例上的功能(後面的),控制器實例的屬性changeName所保存的函數引用也只會更改(調用由jasmine創建的用於跟蹤調用的包裝器函數),而不是觀察器因爲它仍然使用原始函數引用。所以當手表執行時,它只是運行實際的函數引用,而不是後面你在changeName屬性上設置的間諜函數引用。

相反,如果你在你的控制器做到這一點:

var vm = this; 
    $scope.$watch('name', function(){ 
     vm.changeName(); 
    }); 

您將看到您的測試通過。