在指令中测试一个简单的函数,angular
Test a simple function in a directive, angular
这是我的指令:
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");
}));
});
我得到TypeError: undefined is not a function
您需要先编译自定义指令:
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
element = $compile('<position-drop-downs></position-drop-downs>')(scope);
}));
之后应使用 hello
方法填充范围对象:
it('fn hello', inject(function ($compile) {
expect(scope.$$childTail.hello('john')).toBe("hello john");
}));
URD. 注释中的 zeroflagL 提供了更优雅的方式来访问独立的指令范围。你也可以做
expect(element.isolateScope().hello('john')).toBe("hello john");
请注意,您需要访问独立的指令范围。您可以使用 $$childTail
参考。
这是我的指令:
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");
}));
});
我得到TypeError: undefined is not a function
您需要先编译自定义指令:
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
element = $compile('<position-drop-downs></position-drop-downs>')(scope);
}));
之后应使用 hello
方法填充范围对象:
it('fn hello', inject(function ($compile) {
expect(scope.$$childTail.hello('john')).toBe("hello john");
}));
URD. 注释中的 zeroflagL 提供了更优雅的方式来访问独立的指令范围。你也可以做
expect(element.isolateScope().hello('john')).toBe("hello john");
请注意,您需要访问独立的指令范围。您可以使用 $$childTail
参考。