我想用茉莉花和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會自動使它可用?
預先感謝您。也請評論我的測試。
首先您的第一點,請閱讀http://docs.angularjs.org/guide/di的「依賴註釋」部分,尤其是「內聯註釋」。 – 2013-04-24 02:37:40
謝謝。這使得它更清晰。 – 2013-04-24 04:13:05