Problems with Jasmine spyOn toHaveBeenCalled on prototype method

My example of spying on a method does not work with the expected spy handle_click call. when he will pass. However, I get the console log "Foo handle_click called!", So I know that it is being called.

foo.js

function Foo() { this.$btn = $('<a href="#">Foo</a>'); this.$btn.on('click', this.handle_click); }; Foo.prototype.handle_click = function(evt) { evt.preventDefault(); console.log('Foo handle_click called!'); }; 

Foo_spec.js:

 it('should be called when trigger is clicked', function() { var foo = new Foo(); spyOn( foo, 'handle_click' ).andCallThrough(); foo.$btn.click(); expect( foo.handle_click ).toHaveBeenCalled(); }); 

I use jasmine-1.2.0, jasmin-html and jasmine-jquery, but not jasmine-sine; at least I don’t think it is included. Any help is much appreciated!

Update This has been given below. However, I wanted to document the solution in the case of the jQuery plugin:

foo.js:

 function Foo() { ... } Foo.prototype.handle_click = function(evt) { ... } $.fn.foo = function(options) { return new Foo(this, options || {}); }; $.fn.foo.prototype = Foo.prototype; 

Foo_spec.js:

 it('should be called when clicked', function() { spyOn( $.fn.foo.prototype, 'handle_click'); var plugin = $('#selector-for-plugin').foo(); plugin.$btn.click(); expect( plugin.handle_click ).toHaveBeenCalled(); }); 
+6
source share
1 answer

The problem is that you are binding the handle_click function in the constructor. Therefore, when you create a new instance, the function reference is bound to the event. After that, you replace foo.handle_click spy. But this will not affect the function attached to the event, as this is still your original function. You must monitor the Foo.prototype.handle_click function before instantiating, so the spied function can be bound to an event.

 it('should be called when trigger is clicked', function() { spyOn( Foo.prototype, 'handle_click' ); var foo = new Foo(); foo.$btn.click(); expect( foo.handle_click ).toHaveBeenCalled(); }); 
+2
source

Source: https://habr.com/ru/post/944792/


All Articles