我正在尝试使用Jasmine和angularJS app的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);
})) ;
});
所以我测试的是我的数据不是null,是一个数组,至少包含一个项目。由于没有工厂,它失败了。
这是让测试通过的工厂:
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');
}]);
现在我收到一个错误: TypeError:无法设置未定义
的属性'typeOfUnits'为什么控制器不知道范围?我以为DI会自动提供它吗?
提前谢谢你。还请评论我的测试。
答案 0 :(得分:1)
我的代码发现了两个错误:
控制器不知道$ scope。不知道为什么。所以我可以做以下其中一项:
.controller( 'describeUnitController',[ '$范围',函数($范围){ $ scope.typeOfUnits = []; console.log('退出describeUnit'); }]);
OR
.controller('describeUnitController',function describeUnitController($scope){
$scope.typeOfUnits = [];
console.log('exiting describeUnit');
});
我不确定为什么会这样。但是吸取了教训。
然后我尝试按如下方式使用该服务:
.controller('describeUnitController',函数describeUnitController($ scope,GetTypeOfUnit){ $ scope.typeOfUnits = getTypeOfUnit; });
这给了我着名的错误:GetTypeOfUnit的未知提供程序
显然,我必须将服务模块添加到工厂模块才能使用该服务并使测试通过。但是我的app.js已将它们全部定义为:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers','ui.bootstrap','$strap.directives'])
但是由于我正在测试,我还必须在控制器模块中加载服务模块。如果应用程序正在加载(就像在浏览器中一样),我就不必这样做了。
我是否理解正确?谢谢大家。