2014-06-09 29 views
23

我需要測試一個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測試之前運行,並分配在兩個不同的測試中有一個不同的值(我需要將它設置爲第一個爲空,並將值設置爲另一個)。

任何幫助表示讚賞。

謝謝,馬特。

+0

您是否嘗試過將值分配給'$ routeParams.id' ? –

回答

37

可以使用的第二個參數傳遞自定義$routeParams對象$controller(當地人對象),即相同的方式,通過$scope

UserCtrl = $controller('UserCtrl', { 
    $scope: scope, 
    $routeParams: {id: '...'} 
}); 
+0

這是有效的,所以我用來描述函數來測試我的控制器有沒有參數。非常感謝。 – teone

相關問題