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

标签 javascript angularjs unit-testing jasmine karma-runner

为 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/

相关文章:

angularjs - 如何在Angular JS中获取剪贴板数据

javascript - Angular.js 如何在登录 Controller 中设置常量

javascript - Angular js 根据几个条件对项目列表进行排序

angular - 由于未设置 APP_BASE_HREF,在 Angular 6 中测试失败

javascript - 检查列的 checkchange 事件上的单元格编辑

javascript - 为什么我必须单击两次才能使用 jquery 显示 Div?

c# - 在单元测试中使用最小起订量模拟经过身份验证的用户

使用emitAll进行Android流程单元测试

javascript - 具有异步函数的 Sailsjs 策略

javascript - Simple Fancybox 2 键选项 - 如何使用?