我想在指令的link函数内定义的函数中添加spyOn。我在编译元素后尝试了spyOn(element,function_name),但它没有用。
答案 0 :(得分:2)
在指令的范围内公开该功能。
function link (scope, element, attrs) {
// this can be spied on
scope.myFunction = function () {
};
// this won't be able to be spied on
function myPrivateFunction () {
}
}
检索指令的范围。
var directiveScope = angular.element('#myElement').scope();
// or .isolateScope() for isolate scope directives
监视这个功能。
spyOn(directiveScope, 'myFunction');
答案 1 :(得分:0)
您可以使用isolateScope
来实现此目的
//--directive.js--//
(function(angular) {
angular.module('module')
.directive('directive', directive);
directive.$inject = ['dv'];
function directive(dv) {
var directive = {
link: link,
replace: true,
restrict: "E",
scope: {
bindto: '=bindto'
}
};
return directive;
function link(scope, element, attrs) {
scope.generate = generate;
scope.generate();
function generate() {
/**
* Generate code goes here
**/
}
}
}
})(angular);
//--directive.spec.js--//
describe('Unit Test: Line-chart directive', directiveTest);
function directiveTest() {
var dvFactory;
var $compile;
var $scope;
var element;
var compiledElement;
var $isolateScope;
beforeEach(module('module'));
beforeEach(inject(function(_$compile_, _$rootScope_, _dv_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
dvFactory = _dv_;
element = '<directive></directive>';
//Compile the directive element
compiledElement = $compile(element)($scope);
//Obtain an isolateScope of the compiled element
$isolateScope = compiledElement.isolateScope();
}));
it('should call and spy on generate', function() {
//spyOn a generate() in $isolateScope
spyOn($isolateScope, 'generate').and.callThrough();
//Call the method
$isolateScope.generate();
//Check it is called
expect($isolateScope.generate).toHaveBeenCalled();
});
}
&#13;