Как мне издеваться над плагином jQuery? - PullRequest
6 голосов
/ 12 января 2012

Я пишу плагин, который использует существующий плагин, который я хотел бы макетировать.

Плагин, который я пишу, выглядит примерно так:

(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;
}

Хотя фактический экземпляр плагина все еще вызывается.

Ответы [ 2 ]

1 голос
/ 31 марта 2017

Я недавно прошел через Bootstrap модальный и исправил:

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

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

afterEach(()=>{
    delete jQuery.fn.modal
})
0 голосов
/ 12 января 2012

Хорошо. Я только что разработал способ сделать это, я не уверен, что это лучший, но он работает для моих целей.

Я создаю фиктивный плагин в настройках теста следующим образом, с методом для извлечения опций, которые я могу использовать в моем утверждении:

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