2013-04-24 46 views
0

我想用茉莉花和angularJS應用程序的BDD。我的要求是在我的視圖中創建一個select元素,它從工廠獲取數據。所以本着BDD的真實精神,我開始寫作我的觀點之前,先寫我的工廠和控制器。

我的工廠測試:

describe('getTypeOfUnit', function(){ 
    it('should return typeofunits', inject(function(getTypeOfUnit){ 
     expect(getTypeOfUnit).not.toBeNull(); 
     expect(getTypeOfUnit instanceof Array).toBeTruthy(); 
     expect(getTypeOfUnit.length).toBeGreaterThan(0); 
    })) ; 
    }); 

所以我測試,我的數據是不爲空,是一個數組,包含至少一個項目。因爲沒有工廠,所以失敗了。

這是工廠,使測試通過:

angular.module('myApp.services', []) 
    .factory('getTypeOfUnit', function(){ 
     var factory = ['Research Lab', 'Acedamic Unit', 'Misc']; 
     return factory; 
    }); 

現在到控制器。下面是空的控制器:

angular.module('myApp.controllers', []) 
    .controller('describeUnitController',[function($scope){   
     console.log('exiting describeUnit'); 
    }]); 

和試驗控制器:

describe('controllers', function(){ 
    var describeScope; 

    beforeEach(function(){ 
     module('myApp.controllers'); 
     inject(function($rootScope, $controller){ 
      console.log('injecting contoller and rootscope in beforeEach'); 
      describeScope = $rootScope.$new(); 
      var describerController = $controller('describeUnitController', {$scope: describeScope}); 

     }); 
    }) ; 

    it('should create non empty "typeOfUnitsModel"', function() { 
     expect(describeScope["typeOfUnits"]).toBeDefined(); 
     var typeOfUnits = describeScope.typeOfUnits; 
     expect(typeOfUnits instanceof Array).toBeTruthy(); 
     expect(typeOfUnits.length).toBeGreaterThan(0); 
    }); 
}); 

所以我測試我的控制器返回一個非空數組。與服務相同。這些測試失敗。因此,下一步是在控制器中定義的範圍對象上的屬性:

.controller('describeUnitController',[function($scope){ 
     $scope.typeOfUnits = []; 
     console.log('exiting describeUnit'); 
    }]); 

現在,我得到一個錯誤: 類型錯誤:無法設置屬性「typeOfUnits」的未定義

爲什麼控制器不知道關於範圍?我以爲DI會自動使它可用?

預先感謝您。也請評論我的測試。

回答

1

發現了兩個錯誤,我的代碼:

  1. 控制器不知道有關$範圍。不知道爲什麼。因此,我可以執行下列操作之一:

    .controller( 'describeUnitController',[ '$範圍',函數($範圍){$ scope.typeOfUnits = []; 的console.log( '離開describeUnit' ); }]);

OR

.controller('describeUnitController',function describeUnitController($scope){ 
      $scope.typeOfUnits = []; 
      console.log('exiting describeUnit'); 
     }); 

我不知道爲什麼是這樣。但經驗教訓。

  1. 我又試圖按如下方式使用該服務:

    .controller( 'describeUnitController',功能describeUnitController($範圍,GetTypeOfUnit){$ 範圍。typeOfUnits = getTypeOfUnit; });

這給了我著名的錯誤:未知提供商GetTypeOfUnit

Apparantly,我必須將服務模塊添加到工廠模塊才能使用該服務,使測試通過。但我的app.js有他們所有定義:

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers','ui.bootstrap','$strap.directives']) 

但由於我的測試,我必須加載控制器模塊中的服務模塊爲好。如果應用程序正在加載(如在瀏覽器中),我不必這樣做。

我能理解這個嗎?謝謝你們。

+1

首先您的第一點,請閱讀http://docs.angularjs.org/guide/di的「依賴註釋」部分,尤其是「內聯註釋」。 – 2013-04-24 02:37:40

+0

謝謝。這使得它更清晰。 – 2013-04-24 04:13:05

相關問題