我正在尝试使用karma和jasmine测试指令。我正在使用角度1.4,我在这里通过互联网搜索不同的东西,但我无法使它工作。
var angular = require('angular');
module.exports = angular.module('myApp.ui.apps.servicesObject.list', [])
.directive('servicesObjectList', function(){
return {
restrict: 'E',
replace: true,
scope: true,
bindToController: {
services: '=',
selectedServices: '='
},
templateUrl: 'app/ui/apps/services/directives/services.html',
controllerAs: 'servicesListCtrl',
controller: 'ServicesListController'
}
})
.controller('ServicesListController', require('./servicesListController'));
这就是我试图测试它的方式。
describe('Service app test, listDirective' , function(){
var element, scope, controller;
beforeEach(function(){
angular.mock.module('templates');
angular.mock.module('myApp.ui.apps.servicesObject.list', function($provide) {
$provide.value('gettextCatalog', { getString: function(){}});
$provide.value('translateFilter', function(){});
});
});
beforeEach(inject(function($rootScope, $compile, $controller){
scope = $rootScope;
scope.services= _servicesMock_;
element = '<services-object-list selected-services="[]" services="services"></services-object-list>';
$compile(element)(scope);
scope.$digest();
controller = $controller('ServicesListController', {$scope: scope});
console.log(controller.getServices());
}));
it ("First test", function(){
expect(true).toBe(true);
});
});
我遇到的问题是服务在我的控制器中没有绑定,只在范围内。我做错了什么?如果我做控制台(controller.getServices())。它返回undefined而不是我作为属性传递的服务。我的生产代码按预期工作,但没有测试。
非常感谢!
答案 0 :(得分:1)
几个小时之后,我发现角度1.3中添加了一个新功能,以便在unitTesting中更轻松地进行绑定。以下是讨论的主题https://github.com/angular/angular.js/issues/9425
基本上,第三个参数被添加到控制器构造函数服务中,您可以在其中传递绑定到控制器的数据。
所以unitTest配置就是这样。
describe('Service app test, listDirective' , function(){
var element, scope, controller;
beforeEach(function(){
angular.mock.module('templates');
angular.mock.module('myApp.ui.apps.servicesObject.list', function($provide) {
$provide.value('gettextCatalog', { getString: function(){}});
$provide.value('translateFilter', function(){});
});
});
beforeEach(inject(function($rootScope, $compile, $controller){
var data = {
services: _servicesMock_
};
scope = $rootScope;
scope.services= _servicesMock_;
element = '<services-object-list selected-services="[]" services="services"></services-object-list>';
$compile(element)(scope);
scope.$digest();
controller = $controller('ServicesListController', {$scope: scope}, data);
console.log(controller.getServices());
}));
it ("First test", function(){
expect(true).toBe(true);
});
});