【问题标题】:How to mock jQuery Method in Unit-Test for an Angular directive如何在 Angular 指令的单元测试中模拟 jQuery 方法
【发布时间】: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();
});

【问题讨论】:

    标签: angularjs unit-testing


    【解决方案1】:

    在您的示例中“错误:应为间谍,但未定义....”

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

    spyOn(element, 'select');

    阅读更多:http://jasmine.github.io/2.0/introduction.html#section-Spies

    【讨论】:

    • 谢谢!我之前尝试过(应该提到它),但它似乎不起作用。 Expected spy select to have been called.请看这里:jsfiddle.net/m59zocf1/3
    • 我在 html 和 console.log("测试”)在处理程序中。在控制台中我看到它可以工作......测试中有问题......正在调查
    • 如果您在expect(ele.select).toHaveBeenCalled(); 之前添加ele.select();,则测试(显然)通过。 jsfiddle.net/m59zocf1/6
    • 是的,您是否尝试过使用 karma 和 PhantomJS 运行测试?可能是 jsfiddle 中的问题
    • 我已经成功了!看我的更新。在这里找到提示:stackoverflow.com/questions/15720072/…
    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    相关资源
    最近更新 更多