Jasmine expected spy function to have been called on backbone.view

1.2k Views Asked by At

I am having trouble understanding spies with my jasmine tests.

When I run the below test I can see the output CLOSE EVENT in my console, but the test triggers close fails.

How do I write the test correctly using spies?

define([
    'backbone'
], function(Backbone){
    describe('TEST', function(){
        beforeEach(function(){
            this.view = new (Backbone.View.extend({
                initialize: function(){
                    _(this).bindAll('close');
                    this.$el.append($('<span>', {class: 'closeview'}));
                    $('body').append(this.$el);
                    this.$el.on('click', '.closeview', this.close);
                },
                close: function(){
                    console.log('CLOSE EVENT');
                }
            }));
        });
        it('exists', function(){
            expect(this.view.$el).toBeVisible();
        });
        it('triggers close', function(){
            spyOn(this.view, 'close');
            this.view.$el.find('.closeview').trigger('click');
            expect(this.view.close).toHaveBeenCalled();
        });
    });
});
1

There are 1 best solutions below

1
On

When you spy on a function, you are actually stubbing the method. If you just want to check if the function was called but it's important that the content is executed, you need to add:

and.callThrough()

Try to modify your example to:

spyOn(this.view, 'close').and.callThrough();

And see if that helps you with your problem :)