2014-12-27 101 views
2

我初始化我的角度控制器用下面的代碼並沒有改變:

console.log($state.current); 
$location.path('/newpath'); 
console.log($state.current); 

的$ state.current變量不盡管路徑已經改變,但正在改變。我試過$scope.$apply()但這給了我一個消化週期已經在進行中的錯誤。

請注意,這並不在我的測試工作,要麼:

it('should route /newpath to the newpath view', function() { 
    $location.path('/newpath'); 
    $rootScope.$apply(); 

    console.log($location.path()); 
    console.log($state.current); 
    expect($state.current.templateUrl).to.equal('app/newpath/newpath.html'); 

}); 
+0

這3行是否在你的控制器內?如果是的話,那麼在那裏執行的所有代碼只屬於當前狀態...只有當這個範圍被破壞...新的狀態將被啓動... –

+0

是的,你是對的。我在我的控制器中使用全部三條線。但是如何做測試呢?我用我測試規範的代碼更新了我的questiog。 – zszep

+0

但是不應該改變位置反映的狀態?目前我正在將角度路由轉換爲UI路由器。我已經通過$ location.path()設置新位置後,從原始的角度路由器代碼修改了此測試代碼,其中$ route.current.templateUrl已更改。 – zszep

回答

3

失去我的頭髮在這個一整天之後,我終於得到了解決。問題似乎是路由不起作用,因爲我的視圖模板沒有被測試識別。並且ui-router的文檔聲明無效的templateUrl導致路由中斷。將視圖模板放入模板緩存中解決了問題,路由正在運行並且測試通過。只需在規範中加入這行來beforeEach功能:

beforeEach(inject(function ($templateCache) { 
     $templateCache.put('app/newpath/newpath.html', ''); 
    })); 
+0

真的很有趣,很棒的工作,先生! –

0

至於建議由zszep的問題可以通過填充$ templateCache來解決。

beforeEach(inject(function ($templateCache) { 
    $templateCache.put('app/newpath/newpath.html', ''); 
})); 

或者,要模擬的模板取,也可以使用存根$ httpBackend模板請求。

beforeEach(inject(function ($httpBackend) { 
    $httpBackend.when('GET', 'app/newpath/newpath.html').respond(200, ''); 
    $httpBackend.flush(); 
})); 

不要忘記沖水()

您觀察的底層問題是,如果無法加載標記或$ stateProvider定義中定義的所有模板,則轉換將失敗。當發生這種情況時,$ state provider屬性(如$ state.current)不會被填充。

相關問題