为 Angular 控制器运行 Jasmine 单元测试时,它会失败并显示消息
'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 触发?为什么手表在那之后会自行触发?