【发布时间】:2014-11-30 16:12:36
【问题描述】:
我尝试测试一个简单的指令,它使用户能够在单击给定元素后选择整个文本。但我卡住了,因为我不知道如何测试element.select() 的调用。
这是一个可以使用的小提琴:http://jsfiddle.net/m59zocf1/
指令
/**
* @ngdoc directive
* @name Common.directive:clickSelect
* @restrict A
* @element ANY
*/
angular.module('Common').directive('clickSelect', function () {
return {
restrict: 'A',
link: function (scope, element) {
element.bind('click', function () {
element.select();
});
}
};
});
测试
/**
* @module test.Common
* @name clickSelect
*/
describe('Directive: Common.clickSelect', function () {
var ele, scope;
beforeEach(module('Common'));
beforeEach(inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
ele = angular.element('<div><input click-select type="text" class="link" readonly /></div>');
$compile(ele)(scope);
scope.$apply();
}));
it('should render html', function () {
expect(ele.length).toBe(1);
});
it('should select the text after click', function () {
ele.trigger('click');
// does not work.
expect(ele.select).toHaveBeenCalled();
});
});
工作测试用例:
it('should select the text after click', function () {
spyOn($.fn, 'select').and.callThrough();
ele.trigger('click');
scope.$apply();
expect($.fn.select).toHaveBeenCalled();
});
【问题讨论】: