Jasmine spies are not called

I have some problems with espionage in Jasmine

I want to check if a link was clicked on a slider using jasmine spy and jasmine jquery.

Here is a simplified version:

I have some links as part of the html fixture file.

<a href="#" class="someLink">Link 1</a> <a href="#" class="someLink">Link 2</a> 

slider:

 var Slider = function(links){ this.sliderLinks = $(links); this.bindEvents(); } Slider.prototype.bindEvents = function(){ this.sliderLinks.on('click', this.handleClick); } Slider.prototype.handleClick = function(e){ console.log('i have been clicked') } 

spec file:

 describe('Slider', function(){ var slider; beforeEach(function(){ loadFixtures('slider.html'); slider = new Slider('.someLink'); }); it('should handle link click', function(){ spyOn(slider, 'handleClick'); $(slider.sliderLinks[0]).trigger('click'); expect(slider.handleClick).toHaveBeenCalled(); }); }); 

The test does not work. But "I was pressed" was registered on the console, so the method is called.

If I do, the test will pass, though:

 it('should handle link click', function(){ spyon(slider, 'handleClick'); slider.handleClick(); expect(slider.handleClick).toHaveBeenCalled(); }); 

So my question is basically this:

  • Am I testing this type in any other way?
  • Why does the spy not register the fact that the method was called?
+8
jasmine jasmine-jquery
source share
1 answer

I just checked the solution outlined in the comment. Your describe should be:

 describe('Slider', function () { var slider; beforeEach(function () { loadFixtures('slider.html'); spyOn(Slider.prototype, 'handleClick'); slider = new Slider('.someLink'); }); it('should handle link click', function (){ $(slider.sliderLinks[0]).trigger('click'); expect(slider.handleClick).toHaveBeenCalled(); }); }); 

The fact is that you must follow the handleClick prototype before creating the Slider .

The reason is that Jasmine spyOn really does in the code you provided:

 spyOn(slider, 'handleClick'); 

creates the handleClick slider handleClick (containing the spy object) directly on the Slider instance. slider.hasOwnProperty('handleClick') in this case returns true , you know ...

But still there is a handleClick prototype property with which the click event is associated. This means that only the click event handleClick processed by the handleClick prototype, while the native property of the handleClick object of your slider object remains untouched.

So the answer is that the spy does not register the fact that the method was called because it was never called :-)

+17
source share

All Articles