coder
coder

Reputation: 6233

How do you use Jasmine to test a jquery click function to see if it called a custom method?

I'm writing a Jasmine test to determine that a function is called by the JQuery click() method. Where is my logic incorrect? Do I spy on the jquery function or the custom function?

I'm getting an error that reads:

-error

Expected a spy, but got undefined. in http://localhost:8080/...etc.../jasmine.js (line 1253)

-code

describe("funtionCalled", function() {
it("calls the click() function", function() {
    var cc = new CustomClass();
    spyOn($.fn, "click");
    $( '#fieldID' ).click();
    expect(cc.clickFunction()).toHaveBeenCalled();
   });
});

-code being tested

var CustomClass = function(){};

$(document).ready(function(){
    var cf = new CustomClass();

    $( '#fieldID' ).click(function() {  
        cf.clickFunction();
    });
});

CustomClass.prototype.clickFunction = function() {
     //some javascript code
};

Upvotes: 5

Views: 9723

Answers (2)

Mihai Târnovan
Mihai Târnovan

Reputation: 662

You might be missing jasmine-sinon helpers, see https://github.com/froots/jasmine-sinon

Upvotes: 2

Igor Zinov'yev
Igor Zinov'yev

Reputation: 3706

As far as I can tell, you have two things wrong here. First you spy on a wrong object, then you pass the result of the clickFunction method to the expect, not the actual method.

Try this:

describe("funtionCalled", function() {
    it("calls the click() function", function() {
        var cc = new CustomClass();

        spyOn(cc, "clickFunction"); 
        // Notice how you pass a real object and a method name to spyOn

        $('#fieldID').click();

        expect(cc.clickFunction).toHaveBeenCalled();
        // Notice how you pass the method, and not the method call result
    });
});

You can find more on spies in the jasmine wiki.

Upvotes: 7

Related Questions