Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock a jQuery plugin?

I am writing a plugin which uses an existing plugin which I would like to mock out.

The plugin I'm writing looks sort of like this:

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

And I have a Jasmine test which sort of looks like this:

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

This line is where I have tried to mock the plugin:

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

The actual plugin instance is still called though.

like image 488
Charlie Avatar asked Jan 12 '12 11:01

Charlie


1 Answers

I recently went through this with Bootstrap modal and fixed with:

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

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

afterEach(()=>{
    delete jQuery.fn.modal
})
like image 67
ducke1942 Avatar answered Oct 26 '22 05:10

ducke1942