我需要測試一個Controller,它使用$routeParams
來定義它的操作。也許這是一個測試問題,或者是我寫控制器的方式是錯誤的,所以現在我不能寫測試。Angular Test使用RouteParams的控制器
這裏是我的控制器
angular.module('cmmApp')
.controller('UserCtrl', function ($scope, $location, $routeParams, $ionicLoading, $ionicPopup, Userservice) {
//if a user id is set retrieve user information
if(typeof $routeParams.id !== 'undefined'){
var loader = $ionicLoading.show({content: "Retrieving user data"});
var user = Userservice.get({id: $routeParams.id}).$promise;
user.then(function(res){
console.log(res);
$scope.user = res.user;
loader.hide();
});
}
//else create an empty resource
else {
$scope.user = new Userservice;
}
});
基本上我只想加載資源如果提供了id爲$routeParams
,否則創建一個空的資源。
這裏是測試:
'use strict';
describe('Controller: UserCtrl', function() {
// load the controller's module
beforeEach(module('cmmApp'));
var UserCtrl,
scope,
routeParams;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $routeParams, Userservice) {
scope = $rootScope.$new();
routeParams = $routeParams;
UserCtrl = $controller('UserCtrl', {
$scope: scope
});
console.log("routeParams");
routeParams = {id: 8490394};
console.warn(routeParams);
}));
it('should create an epmty user', function() {
console.log(scope.user);
expect(scope.user).toEqual({});
});
});
當我運行grunt test
因緣回覆:
Controller: UserCtrl should create an epmty user FAILED
Expected { } to equal { }.
Error: Expected { } to equal { }.
at null.<anonymous> (/Users/carlopasqualicchio/Sites/CMM_Ionic/test/spec/controllers/user.js:28:24)
我wonering如何告訴因緣改變$routeParams.id
測試之前運行,並分配在兩個不同的測試中有一個不同的值(我需要將它設置爲第一個爲空,並將值設置爲另一個)。
任何幫助表示讚賞。
謝謝,馬特。
您是否嘗試過將值分配給'$ routeParams.id' ? –