我使用指令在输入文件更改时添加了一个侦听器函数,我将在茉莉花中为此创建一个单元测试用例,但无法在单元用例中触发函数。
单元测试代码:
describe('customOnChange', function () {
beforeEach(module('app'));
beforeEach(inject(function ($rootScope, $compile, $parse) {
this.$rootScope = $rootScope;
this.compile = $compile;
this.parse = $parse;
this.initDirective = function (config) {
this.scope = this.$rootScope.$new();
this.scope.listnerFunction = function($event){
console.log("event called : ",$event);
};
this.element = angular.element('<input type="text" name="textField" id="textField" dynamic-data-editor-custom-on-change="listnerFunction($event)" ng-model="testText"/>');
this.compile(this.element)(this.scope);
this.$rootScope.$digest();
$('body').append(this.element);
this.$rootScope.$digest();
};
}));
fit('Applied directive successfully', function() {
this.initDirective();
spyOn(this.scope,'listnerFunction');
var ele = this.element.find("input#textField").eq(0);
console.log('element', ele);
ele.triggerHandler('change');
this.$rootScope.$apply();
expect(this.scope.listnerFunction).toHaveBeenCalled();
});
});
主要指令代码:
function () {
'use strict';
angular.module('app')
.directive('customOnChange', function ($parse) {
return {
restrict: 'A',
link: function ($scope, element, attrs, ngModel) {
var attrHandler = $parse(attrs.dynamicDataEditorCustomOnChange);
var handler = function (e) {
$scope.$apply(function () {
attrHandler($scope, { $event: e });
});
};
element[0].addEventListener('change', handler, false);
}
};
});
})();
运行测试时出现错误 预期会调用间谍列表功能。
请帮助我解决指令的测试用例。
答案 0 :(得分:0)
在您的测试中,问题是:间谍是在调用方法listnerFunction
函数之后创建的,因此您会看到错误。
您应该替换:
this.scope.listnerFunction = function($event){
console.log("event called : ",$event);
};
带有({andCallFake
代表jasmine < 2
)
this.scope.listnerFunction =
jasmine.createSpy("listnerFunction")
.and.callfake(function($event){
console.log("event called : ",$event);
});