2013-08-28 66 views
5

Khi chạy một kiểm tra đơn vị Jasmine cho một bộ điều khiển góc, nó không thành công với thông điệp

'Error: 10 $digest() iterations reached. Aborting!' 

khi $ httpbackend.flush() được gọi.

Đây là bộ điều khiển của tôi:

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

Đây là unittest tôi:

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

});

Khi tôi đặt tham số thứ ba trong $ scope. $ Watch to true, (so sánh đối tượng bình đẳng thay vì tham chiếu), kiểm tra sẽ trôi qua.

Tại sao $ httpbackend.flush() khiến đồng hồ $ kích hoạt? Và tại sao đồng hồ tự kích hoạt sau đó?

+0

'submitVenue' được xác định ở đâu? – zsong

+0

Nó được cho là submitStuff(). Hàm đó được định nghĩa trong bộ điều khiển. Cảm ơn. Thay đổi câu hỏi cho phù hợp. – Torleif

+1

Hãy nhìn vào điều này, điều này có thể hữu ích. Nó không liên quan đến các xét nghiệm của bạn. http://stackoverflow.com/questions/13594732/maxing-out-on-digest-iterations?rq=1 – zsong

Trả lời

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