0

I am trying to test some javascript code (BackBone View) using jasmine

Here is the function within the defined BackBone view I am trying to test:

var aView = Backbone.View.extend({

events: {
       'click #btn': 'update'
        } 

update: function(e){
    e.preventDefault();
    $.ajax({
    ....
    });
}

});

So, to test the function I am trying to call the function and then spyOn $.ajax to see if it was called with appropriate url. But, the problem is I cannot pass the event into the function so that it carries out the ajax.

Here's the jasmine code block:

it("tests update ajax", function() {

             spyOn($, "ajax");

             //Call update function
            this.aView.update(this.aView.$("#btn").trigger("click"));

            expect($.ajax).toHaveBeenCalled();

});

Here's the error I am currently receiving:

TypeError: Object [object Object] has no method 'preventDefault'

I hope I have provided all the information necessary and the question is precise :)

4

1 回答 1

2

您不应该直接调用更新方法。如果您触发事件,它将调用更新方法。

以下应该删除您当前的错误:

it("tests update ajax", function() {

        this.aView.$el.find('.update').trigger("update");
        this.aView.update(this.aView.$("#btn").trigger("click"));

});

如果你的观点是这样的:

var aView = Backbone.View.extend({

  events: {
    'click a.update' : 'update'
  },

  update: function(e){
    e.preventDefault();
    $.ajax({
      ....
    });
  }
});

这样您还可以检查您的视图事件是否设置正确。

于 2013-09-20T19:05:19.533 回答