Angularjs 测试指令中的简单函数,角度
这是我的指示:Angularjs 测试指令中的简单函数,角度,angularjs,unit-testing,karma-jasmine,Angularjs,Unit Testing,Karma Jasmine,这是我的指示: angular.module('clientApp') .directive('positionDropDowns', function (CommonFactory) { return { templateUrl: 'template/position-drop-downs/position-drop-downs.html', restrict: 'E', scope: { districtsWithSubObje
angular.module('clientApp')
.directive('positionDropDowns', function (CommonFactory) {
return {
templateUrl: 'template/position-drop-downs/position-drop-downs.html',
restrict: 'E',
scope: {
districtsWithSubObjects: '='
},
link: function postLink(scope, element, attrs) {
scope.hello = function(name){
return 'hello ' + name;
}
}
};
});
如何测试hello
功能?我试过这个:
describe('Directive: positionsDropDowns', function () {
// load the directive's module
beforeEach(module('clientApp'));
beforeEach(module('template/position-drop-downs/position-drop-downs.html'));
var element,
scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
element = angular.element('<position-drop-downs></position-drop-downs>');
$rootScope.$digest();
}));
it('fn hello', inject(function ($compile) {
expect(element.scope.hello('john')).toBe("hello john");
}));
});
description('Directive:positionsDropDowns',function(){
//加载指令的模块
在每个模块之前(模块('clientApp');
每个模块之前(模块('template/position drop-downs/position drop-downs.html');
var元素,
范围
beforeach(注入(函数($rootScope){
scope=$rootScope.$new();
元素=角度。元素(“”);
$rootScope.$digest();
}));
它('fn hello',inject(函数($compile)){
expect(element.scope.hello('john')).toBe(“hello john”);
}));
});
I get
TypeError:undefined不是函数
您需要首先编译自定义指令:
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
element = $compile('<position-drop-downs></position-drop-downs>')(scope);
}));
URD.zeroflagL在注释中提供了访问独立指令范围的更优雅的方式。你也可以
expect(element.isolateScope().hello('john')).toBe("hello john");
注意,您需要访问独立的指令作用域。您可以使用
$$childTail
引用来完成此操作。尝试元素.scope()。您好('john')
这是jquery/jqlite插件。您可以使用$$childTail引用或元素.isolateScope()
@zeroflagL来完成此操作。谢谢,这很有用。不知道有关isolateScope
。
expect(element.isolateScope().hello('john')).toBe("hello john");