【问题标题】:Angular directive test throws an errorAngular 指令测试抛出错误
【发布时间】:2012-11-21 11:15:56
【问题描述】:

这是包装 jquery-ui 自动完成的指令

angular.module('myApp.directives', [])
    .directive('autocomplete', function () {
        return {
            restrict: 'E',
            replace: true,
            transclude: true,
            template: '<input ng-model="autocomplete" type="text"/>',
            link: function (scope, element, attrs) {
                scope.$watch(attrs.typedvalue, function () {
                    element.autocomplete({
                        search: function (event) {
                            scope[attrs.typedvalue] = this.value;
                            scope[attrs.fullselection] = '';
                            scope[attrs.selectionid] = '';
                            scope[attrs.shortselection] = '';
                            scope.$apply();
                        },
                        source: scope.fetchList,
                        select: function (event, ui) {
                            scope[attrs.fullselection] = ui.item.label;
                            scope[attrs.selectionid] = ui.item.itemId;
                            scope[attrs.shortselection] = ui.item.value;
                            scope.$apply();
                        }
                    });
                });
            }
        };
    });

我正在尝试使用以下测试对其进行单元测试(按照此处https://github.com/vojtajina/ng-directive-testing 的说明进行操作):

describe('Directives', function () {

    beforeEach(module('myApp.directives'));

    describe('autocomplete directive', function () {
        var elm, scope;
        beforeEach(inject(function ($rootScope, $compile) {
            elm = angular.element('<autocomplete fullselection="fullDstn" shortselection="dstn" selectionid="geonameId" typedvalue="typedValue" id="DstnSlctr"/>');
            scope = $rootScope;
            $compile(elm)(scope);
            scope.$digest();
        }));

        it('should create input', inject(function ($compile, $rootScope) {
            expect(elm.id).toBe('DstnSlctr');
            expect(elm.prop('tagName')).toBe('INPUT');
            debugger;
        }));
    });
});

但我得到一个错误:

        TypeError: Object [[object HTMLInputElement]] has no method 'autocomplete'
            at Object.fn (C:/Users/kmukhort/Documents/_files/TMate/AngularTest/a
pp/js/directives.js:13:33)

就行 element.autocomplete({ 我怀疑在 $compile 时 jquery-ui 功能没有附加到元素上。 我指的是 testacular.config 中的 jquery-ui 库

basePath = '../';

files = [
...
  'app/lib/jquery-ui-*.js',
];

请你告诉我我做错了什么?

谢谢! 克塞尼亚

【问题讨论】:

    标签: unit-testing autocomplete angularjs directive


    【解决方案1】:

    我认为你需要更换:

    element.autocomplete(...);
    

    与:

    $(element).autocomplete(...);
    

    【讨论】:

      猜你喜欢
      • 2017-08-24
      • 2017-08-21
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2019-10-10
      • 2019-12-24
      • 2015-04-28
      • 1970-01-01
      相关资源
      最近更新 更多