Charlie
Charlie

Reputation: 10307

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.

Upvotes: 7

Views: 2338

Answers (2)

ducke1942
ducke1942

Reputation: 101

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

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

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

afterEach(()=>{
    delete jQuery.fn.modal
})

Upvotes: 6

Charlie
Charlie

Reputation: 10307

Ok. I just worked out a way to do it, I'm not sure if it's the best but it works for my purposes.

I create a mock plugin in the test setup like this, with a method to retrieve the options which I can use in my assert:

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

Upvotes: 0

Related Questions