我如何模拟jQuery插件?

Cha*_*lie 7 jquery unit-testing jquery-ui mocking

我正在编写一个使用现有插件的插件,我想嘲笑它.

我写的插件看起来像这样:

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

我有一个Jasmine测试,看起来像这样:

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");
  });
});
Run Code Online (Sandbox Code Playgroud)

这行是我试图模拟插件的地方:

jQuery.pluginWhichShouldBeMocked = function(options){
  passedOptions = options;
}
Run Code Online (Sandbox Code Playgroud)

但仍会调用实际的插件实例.

小智 6

我最近使用 Bootstrap 模态完成了这个并修复了:

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

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

afterEach(()=>{
    delete jQuery.fn.modal
})
Run Code Online (Sandbox Code Playgroud)


Cha*_*lie 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");
  });
});
Run Code Online (Sandbox Code Playgroud)