2

I have a javascript function deleteSomething(), within which the load() function in jQuery is called.

function deleteSomething(a, b){
    deleteIt(a, b, function(success){
        if(success){
            $("#table").load(...);        
        }
    })
}

Now I want to test deleteSomething() with Jasmine to see if load() is being called. But got Error: Expected a spy, but got Function

describe("deleteSomething", function() {
    beforeEach(function () {
        ...
    });
    it("should call load() when deleteIt returns true", function() {
        spyOn($('#table'), 'load'));

        deleteIt.and.callFake(function(a, b, callback){
            callback(true);
        });
        deleteSomething(a, b);

        expect($('#table').load).toHaveBeenCalled();
    });
});

I'm new to Jasmine, how should I do this?

1 Answers1

3

You need to spy on jQuery prototype, it is available here: $.fn.

So your code should look something like this:

describe("deleteSomething", function() {
  it("Should call load", function() {
      //$.fn is where the load function is defined
      //  $("...") returns a new jQuery.fn instance that has load function
      //  from jQuery.fn.prototype
      spyOn($.fn, 'load');
      $("#anything").load();
      expect($.fn.load).toHaveBeenCalled();
  });
});

Some more information about the difference of object own members and prototype members (inherited) can be found here.

HMR
  • 37,593
  • 24
  • 91
  • 160
  • How do you test if load() is being called on the correct element? – Jenny Saqiurila Nov 28 '17 at 22:52
  • 1
    @JennySaqiurila `expect($.fn.load.calls.argsFor(0)[0]).toBe("#table");` https://stackoverflow.com/a/21873859/1641941 (first comment) – HMR Nov 29 '17 at 02:43
  • Thx for the information! I managed to make it work like this: `expect($.fn.load.calls.mostRecent().object[0]).toBe(document.getElementById("table"));` – Jenny Saqiurila Nov 29 '17 at 15:02