2016-03-03 29 views
1

有人可以指導我如何測試角度$viewContentLoaded。我在我的控制器上有一個$watch

我相關的控制器代碼:

$scope.$watch('$viewContentLoaded', function() { 
      $scope.variableOne= true; 
     }); 

這裏是我的相關茉莉花規格:

describe('Testing $viewContentLoaded', function() { 
      it('should be true', inject(function ($controller,$scope) { 
       $controller('MainCtrl'); 

       // what to do to invoke $viewContentLoaded ??? 

       $scope.$digest(); 
       expect($scope.variableOne).toBe(true); 
      })); 
     }); 

Plunkr code

任何幫助,這將不勝感激!

回答

1

$viewContentLoaded僅當DOM加載時纔會觸發事件。所以不知何故,您需要通過分配MainCtrl範圍來獲取DOM。

爲此,我會說添加一個虛擬divng-controller="MainCtrl"分配給它。然後用MainCtrl範圍編譯該div。所以,一旦你編譯該div,在編譯該div後,它將廣播$viewContentLoaded將被偵聽器監聽(這就是爲什麼虛擬DOM在這裏很重要)。

代碼

var $scope; 
describe('Testing $viewContentLoaded', function() { 
    it('should be true', inject(function($controller, $rootScope, $compile) { 
    $scope = $rootScope.$new(); 
    $controller('MainCtrl', { 
     $scope: $scope 
    }); 
    var div = '<div ng-controller="MainCtrl"></div>' 
    $compile(div)($scope); 
    $scope.$digest(); 
    expect($scope.variableOne).toBe(true); 
    })); 
}); 

Demo Here

注:$viewContentLoaded事件應放置在聽衆像$scope$scope.$on,而不是把守着 它來聽。

+0

_Nice!此解決方案工作。 Thanks._你能告訴我爲什麼我需要從'$ rootScope'創建一個新的'$ scope'來與'$ compile'一起使用,而不僅僅是模擬它呢? – vas

0

你也可以做(假設你已經使用$ $範圍上,而不是$留意$ viewContentLoaded):

$scope.$broadcast('$viewContentLoaded'); 

這可以防止加載任何DOM