DLS
DLS

Reputation: 5491

How to test custom events with Jasmine (using Backbone)

I have a function below that is bound to a button click. Code below part of TeaserView class.

addCard: function() {
   if(!this.model.get("loggedIn")){
      Backbone.pubSub.trigger("Signup");
      return;
    }

     this.showAddCardDialog();
  }

This is my test method

it("Should trigger signup event when clicked and not logged in", function(){
   Backbone.pubSub = _.extend({}, Backbone.Events);
   signupCallback = jasmine.createSpy("Signup");
   //Backbone.pubSub.on("Signup", signupCallback);
   teaserView = new TeaserView({
     el: "#teaser",
            model: this.model //was created in setup call
     });

     $("#addCard").trigger("click");
     expect(signupCallback).toHaveBeenCalled();
    });

But my test to check if the Backbone.pubSub custom event was called fails. How do I test the listening for this event correctly?

Upvotes: 3

Views: 1481

Answers (1)

mahercbeaucoup
mahercbeaucoup

Reputation: 597

Your given test code isn't actually listening to the signup event.

signupCallback = jasmine.createSpy("Signup");

Isn't what you want.

signupCallback = jasmine.createSpy();    
Backbone.pubSub.on('Signup', signupCallback);

Should get you what you want.

In this new code, the signupCallback is being assigned as an event callback, so triggering the event should call the spy callback.

Upvotes: 1

Related Questions