如何在单元测试中为Angular指令模拟jQuery方法

时间:2014-11-30 16:12:36

标签: angularjs unit-testing

我尝试测试一个简单的指令,该指令允许用户在点击该给定元素后选择整个文本。但我陷入困境,因为我无法弄清楚如何测试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();
});

1 个答案:

答案 0 :(得分:1)

在你的例子中“错误:期待间谍,但未定义......”

你应该在element.select方法上使用spy:

spyOn(element, 'select');

了解详情:http://jasmine.github.io/2.0/introduction.html#section-Spies