2013-08-28 9 views
5

角コントローラのジャスミンユニットテストを実行するとき、それはメッセージ

$ httpbackend.flush()が呼び出され
'Error: 10 $digest() iterations reached. Aborting!' 

で失敗します。

これは私のコントローラである。

theApp.controller("myCtrl", function($scope, $http, globalstate){ 
    $scope.currentThing = globalstate.getCurrentThing(); 
     $scope.success = false; 

    $scope.$watch(globalstate.getCurrentThing, function(newValue, oldValue){ 
      $scope.currentThing = newValue; 
    }); 

    $scope.submitStuff = function(thing){ 
      $http.put('/api/thing/PutThing', thing, {params: {id: thing.Id}}) 
      .success(function(){   
       $scope.success = true; 
      }) 
    }; 
}); 

これは私のユニットテストである:

describe('myCtrl', function(){ 

    var myController = null; 
    beforeEach(angular.mock.module('theApp')); 

    beforeEach(inject(function($injector){ 
     $rootScope = $injector.get('$rootScope'); 
     scope = $rootScope.$new(); 

     $httpBackend = $injector.get('$httpBackend'); 

     $controllerService = $injector.get('$controller'); 
     mockGlobalState = { 
      getCurrentThing : function(){ 
       return {Id: 1, name: 'thing1'}; 
      } 
     }; 

     $controllerService('myCtrl', {$scope: scope, globalstate: mockGlobalState}); 
    })); 

    it('should set flag on success', function(){ 
     var theThing = {Id: 2, name: ""}; 
     $httpBackend.expectPUT('/api/thing/PutThing?id=2',JSON.stringify(theThing)).respond(200,''); 

     scope.submitStuff(theThing, 0); 

     $httpBackend.flush(); 

     expect(scope.basicupdateSucceeded).toBe(true); 
    }); 

})。

$ scope。$ watchの3番目のパラメータをtrueに設定した場合(参照ではなくオブジェクトの等価を比較)、テストに合格します。

なぜ$ httpbackback.flush()は$ watchをトリガさせますか? それから、なぜ時計はそれ自身の引き金となるのでしょうか?

+0

「submitVenue」はどこに定義されていますか? – zsong

+0

これはsubmitStuff()とされていました。その機能はコントローラーで定義されています。ありがとう。それに応じて質問を変更しました。 – Torleif

+1

これを見て、これは多分役立つかもしれません。あなたのテストには関係しません。 http://stackoverflow.com/questions/13594732/maxing-out-on-digest-iterations?rq=1 – zsong

答えて

0
// **when you are assigning something to currentThing, it will trigger watch** 
$scope.currentThing = globalstate.getCurrentThing(); 
$scope.success = false; 

$scope.$watch(globalstate.getCurrentThing, function(newValue, oldValue){ 
    // **here you are changing the item to whom you are watching so it can cause recursion.** 
    $scope.currentThing = newValue; 
});