Reputation: 5638
I got a weird error when testing the trigger method of my Backbone model. Below is my code:
Category = Backbone.Model.extend({
fetchNotes: function() {
this.trigger("notesFetchedEvent");
}
})
describe("Category", function() {
it("should fetch notes", function() {
var category = new Category;
spyOn(category, "trigger");
category.fetchNotes();
expect(category.trigger).wasCalledWith("notesFetchedEvent");
})
})
The error I got was "Expected spy trigger to have been called with [ 'notesFetchedEvent' ] but was called with ...jibberish...". Does anyone know how to fix this? Thanks.
Upvotes: 3
Views: 3000
Reputation: 2638
I've found that often the best way to test event triggering is to register a spy as one of the listeners on the event instead of spying on the trigger method directly. This would look something like this:
describe("Category", function() {
it("should fetch notes", function() {
var category = new Category();
var spy = jasmine.createSpy('event');
category.on('notesFetchedEvent', spy);
category.fetchNotes();
expect(spy).toHaveBeenCalled();
});
});
Upvotes: 4