2012-01-12 35 views
5

Tôi đang viết một plugin sử dụng plugin hiện có mà tôi muốn giả lập.Tôi làm cách nào để tạo một plugin jQuery?

Plugin Tôi đang viết trông loại như thế này:

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

Và tôi có một bài kiểm tra Jasmine mà loại trông như thế này:

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"); 
    }); 
}); 

dòng Đây là nơi tôi đã cố gắng để giả lập plugin:

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

Ví dụ plugin thực tế vẫn được gọi.

Trả lời

0

Ok. Tôi chỉ làm việc ra một cách để làm điều đó, tôi không chắc chắn nếu nó là tốt nhất nhưng nó hoạt động cho mục đích của tôi.

tôi tạo một plugin giả trong thiết lập thử nghiệm như thế này, với một phương pháp để lấy các tùy chọn mà tôi có thể sử dụng trong khẳng định của tôi:

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

Gần đây tôi đã trải qua điều này với Bootstrap phương thức và cố định với:

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

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

afterEach(()=>{ 
    delete jQuery.fn.modal 
}) 
Các vấn đề liên quan