2015-04-20 94 views
0

我目前有一個問題,寫一些控制器的測試。在下面的beforeEach塊中,我需要實例化一個activityController並注入作用域對象。我在調用$ controller服務之前添加了一個控制檯日誌,然後輸出這個日誌,但是之後的日誌永遠不會被調用,因此$controller塊中的內容被打破了。茉莉花測試中未定義的角度控制器

beforeEach(inject(function($controller) { 
    console.log(activityController); 

    activityController = $controller('activityController', { 
     '$scope': $scope 
    }); 

    console.log("TEST"); 
})); 

在我的測試中,我看到Type Error: activityController is undefined in C:\.......\activity.controller.test.js,所以我知道它絕對沒有被實例化。

enter image description here

我已經在這裏創造的相關文件的要點:https://gist.github.com/junderhill/e181ce866ab1ebb1f805

沒有被正確實例化的活動控制器引起我的測試失敗。任何想法可能會造成這一點,將不勝感激。謝謝

回答

1

傑森。

嘗試在創建控制器時設置activityService,因爲您還應該注入所有服務。

+0

我試過這個,它似乎沒有任何區別。錯誤消息保持不變,第二個'console.log'未被命中。 –

+0

也許你忘了在'beforeEach'中設置'currentTeam'? –

+0

我想我正在接近解決這個問題。看來,設置currentTeam的請求並沒有及時返回,因爲當我實例化控制器時,它正在崩潰。我需要嘲笑角色服務以及我認爲目前我使用真正的服務。 –

0

看起來這行可能導致問題:

mockRoleService.setCurrentRole({"AssignmentID":21,"EndDate":"2049-12-31T00:00:00","StartDate":"2000-01-01T00:00:00","UserType":1,"AccessLevel":"00000000-0000-0000-0000-000000000000","Description":"Demonstration Territory 1","TeamID":null}); 

它看起來像您使用的roleService的實際注入的版本,而不是存根文字的,所以它實際上是要火了您的實現,這是...

this.setCurrentRole = function(role){ 
currentRole = role; 
$http.get("http://localhost:14938/api/User/GetTeamForAssignment?assignmentId=" + role["AssignmentID"] + "&assignmentType=" + role["UserType"]) 
.success(function (data) { 
    currentTeam = data; 
}); 

}

如果你要直接與$ httpBackend模擬使用該服務,其實我換爲o在$ q.defer()中執行,因爲目前就是這樣,這是一個異步調用。您需要完成該操作才能正確設置currentTeam。所以,也許像..

this.setCurrentRole = function(role){ 
var deferred = $q.defer(); 
currentRole = role; 
$http.get("http://localhost:14938/api/User/GetTeamForAssignment?assignmentId=" + role["AssignmentID"] + "&assignmentType=" + role["UserType"]) 
.success(function (data) { 
    currentTeam = data; 
    deferred.resolve(); 
}); 
return deferred.promise; 

}

而且顯然做了某種deferred.reject如果事情靠不住來自HTTP回來。

希望有幫助!

埃裏克