当为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触发? 为什么手表会在此之后触发?
答案 0 :(得分: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;
});