Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
};
like image 672
coder Avatar asked Jun 28 '11 22:06

coder


People also ask

What is Jasmine jQuery?

jasmine-jquery. jasmine-jquery provides two extensions for the Jasmine JavaScript Testing Framework: a set of custom matchers for jQuery framework. an API for handling HTML, CSS, and JSON fixtures in your specs.

What is click in jQuery?

jQuery click() Method The click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.

How do you click a button in JQ?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


1 Answers

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.

like image 59
Igor Zinov'yev Avatar answered Nov 15 '22 07:11

Igor Zinov'yev