2016-04-20 48 views
0

我想单元测试$scope.$watch在控制器中,我不知道为什么$scope.$apply()在测试代码导致意外的请求错误,如Error: Unexpected request: GET /locales/en.json。这是控制器的其他部分,它为什么涉及这里?

但是,如果我评论$scope.$apply,则不会发生此错误,但当然在这种情况下无法触发$ watch。我是否需要嘲笑像$httpBackend.whenGET('/locales/en.json').respond('');这样的请求?

控制器:

$scope.$watch(function(){ 

    return $location.path(); 

    }, function() { 

    $scope.currentPath = $location.path().match(/\/[a-z0-9A-Z_]*/)[0]; 

    $scope.currentNav = 'menu.' + $scope.currentPath.replace('/', ''); 

}); 

茉莉:

describe('homeController', function() { 
    beforeEach(module('homeApp')); 

    var $rootScope, $scope, controller, $httpBackend, $location, $route, $window 

    beforeEach(inject(function($controller, _$rootScope_, _$httpBackend_, _$location_, _$route_, _$window_) { 
     $rootScope = _$rootScope_; 
     $scope = $rootScope.$new(); 
     controller = $controller('homeController', {$scope: $scope}); 
     $httpBackend = _$httpBackend_; 
     $location = _$location_; 
     $route = _$route_; 
     $window = _$window_; 
    })); 

    describe('watch path', function() { 

     it('should change currentPath and currentNav', function() { 
      $location.path('/dashboard'); 
      $scope.$apply(); 

      $location.path('/images'); 
      $scope.$apply(); 

      expect($scope.currentPath).toBe('/images') 
      expect($scope.currentNav).toBe('menu.images') 
     }) 
    }) 
}) 

更新

它嘲讽所需要的所有的http请求后工作。但仍然想知道为什么它会影响这些请求。

+0

作为'$ scope.watch'需要在这里调用'$ scope.apply'的参数是你的$ scope.watch导致问题 –

回答

0

在上面的例子中,你没有看任何东西。 $ watch函数将在被监视对象的值发生变化时被调用。它会为你返回新旧对象的价值。

$scope.someValue = 0; 

    $scope.$watch(
    "$scope.someValue", 
    function handleFooChange(newValue, oldValue) { 
    console.log("$scope.someValue:", newValue); 
    } 
); 

这里someValue正在观察变化。 someValue的值一旦改变,$ watch的回调函数将被调用。