2013-08-28 45 views
5

当运行一个茉莉单元测试用于角控制器,它失败消息

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

当$ httpbackend.flush()被调用。

这是我的控制器:

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中的第三个参数设置为true(比较对象相等性而不是引用)时,测试通过。

为什么$ httpbackend.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; 
}); 
相关问题