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

I am writing a Jasmine test to determine that a function is called by the JQuery click () method. Where is my logic wrong? Am I looking at a jquery function or a custom function?

I get an error message:

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

- test code

 var CustomClass = function(){}; $(document).ready(function(){ var cf = new CustomClass(); $( '#fieldID' ).click(function() { cf.clickFunction(); }); }); CustomClass.prototype.clickFunction = function() { //some javascript code }; 
+4
source share
2 answers

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

Try the following:

 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 about spies in the jasmine wiki .

+6
source

You may not have enough jasmine-silon assistants, see https://github.com/froots/jasmine-sinon

+1
source

All Articles