开发者

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 j开发者_如何转开发query 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
};


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜