gpt4 book ai didi

javascript - 为什么 $httpbackend.flush 会导致我的 $scope.$watch 无限期触发?

转载 作者:搜寻专家 更新时间:2023-11-01 04:41:59 25 4
gpt4 key购买 nike

为 Angular Controller 运行 Jasmine 单元测试时,它失败并显示消息

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

当调用 $httpbackend.flush() 时。

这是我的 Controller :

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?为什么之后 watch 会自动触发?

最佳答案

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

关于javascript - 为什么 $httpbackend.flush 会导致我的 $scope.$watch 无限期触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18487835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com