2012-01-12 18 views
5

我正在寫一個插件,它使用我想要模擬出的現有插件。我該如何模擬一個jQuery插件?

我寫的插件看起來有點像這樣:

(function($){ 
    $.widget("myPlugin",{ 
    _create: function(){ 
     var otherControl = $("<div></div>"); 
     otherControl.pluginWhichShouldBeMocked({foo: "bar"}); 
     this.element.append(otherControl); 
    } 
    }); 
})(jQuery); 

而且我有一個茉莉花測試,看起來有點像這樣:

describe("When creating", function(){ 
    var element; 
    var passedOptions; 
    beforeEach(function(){ 
    jQuery.pluginWhichShouldBeMocked = function(options){ 
     passedOptions = options; 
    } 
    element = $("<div></div>"); 
    element.myPlugin(); 
    }); 

    it("should create the other plugin and pass 'bar' to it as the foo parameter", function(){ 
    expect(passedOptions.foo).toEqual("bar"); 
    }); 
}); 

這行是我曾嘗試模擬插件:

jQuery.pluginWhichShouldBeMocked = function(options){ 
    passedOptions = options; 
} 

雖然實際的插件實例仍然被調用。

回答

0

好的。我只是想出了一個辦法,我不確定它是否是最好的,但它適用於我的目的。

創建測試設置這樣的模擬插件,提供檢索,我可以在我的斷言使用的選項的方法:

describe("When creating", function(){ 
    var element; 
    var passedOptions; 
    beforeEach(function(){ 
    $.widget("pluginWhichShouldBeMocked",{ 
     getOptions: function(){ 
     return this.options; 
     } 
    }); 
    element = $("<div id='extenalPlugin'></div>"); 
    element.myPlugin(); 
    }); 

    it("should create the other plugin and pass 'bar' to it as the foo parameter", function(){ 
    expect(element.find("div#externalPlugin").pluginWhichShouldBeMocked("getOptions").foo).toEqual("bar"); 
    }); 
}); 
0

最近,我通過這個去與引導模式和固定的:

beforeEach(()=>{ 
    jQuery.fn.modal =() => {} 
}) 

describe(()=>{ 
    \\ ... do your thing 
}) 

afterEach(()=>{ 
    delete jQuery.fn.modal 
}) 
相關問題