jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了我如何模拟jQuery插件?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个使用现有插件插件,我想嘲笑它.

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

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

我有一个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");
  });
});

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

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

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

解决方法

好.我只是想办法做到这一点,我不确定它是否是最好的,但它适用于我的目的.

在这样的测试设置中创建了一个模拟插件,并使用一种方法来检索我可以在我的断言中使用的选项:

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

大佬总结

以上是大佬教程为你收集整理的我如何模拟jQuery插件?全部内容,希望文章能够帮你解决我如何模拟jQuery插件?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: