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
};
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With