2014-03-06 24 views
0

我有一個按以下方式定義的控制器,它的工作原理非常完美。但是,當我嘗試測試該控制器它說,「(控制器名稱)」不是一個函數,得到了不確定的」。如何測試這種方法定義控制器。如何測試在angularjs中通過module.config創建的控制器

controller.js

var mainModule = angular.module('module1'); 

function home($scope) { 
    $scope.test = "hello"; 
} 
home.$inject = ["$scope"]; 

mainModule.config(['$routeProvider', 
    function ($routeProvider) { 
     $routeProvider.when('/', { 
      templateUrl: 'partials/home.html', 
      controller: home 
     }); 
    } 
]); 

testSpec.js

describe("Test home controller", function() { 
    beforeEach(module('module1')); 
    it("test the controller ", inject(function ($rootScope, $controller) { 
     var ctrl = $controller("home", { 
      $scope: $rootScope 
     }); 
     expect($rootScope.items.length).toBe(3); 
    })); 
}); 
+2

您大概可以使用['$ injector.instantiate'](http://docs.angularjs.org/api/auto/service/$injector)創建一個新的'home'控制器實例。但是,你有什麼理由在全球範圍內創建控制器? [官方文檔](http://docs.angularjs.org/guide/controller)顯然不鼓勵(檢查第一個註釋)。 –

+0

沒有它在全球範圍內,我有很多模塊,它像每個模塊的基礎。你能否詳細說明或指出我如何使用$ injector.instantiate – SpreeTheGr8

+1

在你發佈的代碼中,'home'是在全局範圍內聲明的。你的代碼應該已經可以工作了,因爲['$ controller'](http://docs.angularjs.org/api/ng/service/$controller)服務檢查全局窗口對象上的'window [constructor]'。但顯然'window ['home']'是'undefined'。 –

回答

1

正如@PaoloMoretti在評論中提到的,你不應該定義在全局範圍控制器(除非原型)相反definie控制器作爲模塊的一部分:

var mainModule = angular.module('module1'); 

mainModule.controller('home', function($scope) { 

    $scope.test = "hello"; 
}); 

然後,當你使用這條線測試:

beforeEach(module('module1')); 

控制器將可用於測試。

相關問題