2

在我的 QUnit 测试中,我想模拟自动完成方法(jQuery UI),但每次我运行测试时都像:

test("Create_PassedContainer_RunsAutocompleteOnMatchingElement",function(){
    var $matchingInput = $('<input data-autocomplete-url="some"/>');
    var $dom = $('<div><input/></div>');
    $dom.append($matchingInput);
    var autocompleteWasCalled = false;
    $matchingInput.autocomplete = function(){ autocompleteWasCalled = true; };

    new Autocomplete($dom);

    ok(autocompleteWasCalled,"Should call autocomplete.");
});

我得到结果:

TypeError: Object [object Object] has no method 'autocomplete'.

被测代码:

function Autocomplete($container) {
    var $self = this;

    this.Initialize = function($container) {
        $self.$container = $container;
        $self.$text = $('*[data-autocomplete-url]', $container);
        $self.$value = $('input[type="hidden"]', $container);

        $self.$text.autocomplete();
    };

    $self.Initialize($container);
};

任何事情都会有所帮助。

4

1 回答 1

2

自动完成是一个插件,试试这个:

var oldAutocomplete = $.fn.extend(true, {}, $.autocomplete);
$.autocomplete = function(){
    autocompleteWasCalled = true;
}

/// Other code...

$.fn.autocomplete = oldAutocomplete;
于 2012-08-20T14:54:45.797 回答