Jasmine spies not being called

前端 未结 1 710
鱼传尺愫
鱼传尺愫 2021-01-11 20:43

I am having some trouble implimenting spying in Jasmine

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

Here i

相关标签:
1条回答
  • 2021-01-11 20:57

    I've just verified 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 point is that you have to spy on prototype handleClick function and before the Slider creation.

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

    spyOn(slider, 'handleClick');
    

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

    But still, there is handleClick prototype property to which your click event is bound. That means just triggered click event is handled by the prototype handleClick function while the slider object own property handleClick (your spy) stays untouched.

    So the answer is that the spy is not registering the fact that the method has been called because it has never been called :-)

    0 讨论(0)
提交回复
热议问题