问题
I'm just getting started testing my Backbone app with Sinon and Jasmine. I have a view that look something like (coffeescript):
initialize: ->
@collection.on 'reset', @render, this
render: ->
if @collection.fetched
# do stuff
else
@$el.append "<h3>Loading...</h3>"
@collection.fetch()
this
I want to test this with an unfetched collection, but I'm not sure how to fake an ajax call within my code (obviously can easily be done in the spec). I realize that I could just pass in a pre-fetched collection, but I'm curious -- is it possible with Sinon to override the fetch function to return a fake response?
Thank you for any help.
回答1:
Under the hood, Backbone uses jQuery's $.ajax
method, so you can stub that out. We use this to catch accidental calls in our Jasmine specs:
$.ajax = -> throw "ajaxShouldBeStubbedOutError: #{JSON.stringify arguments}"
And then you can stub over that if you want to fake an AJAX call and its response:
spyOn($,'ajax').andCallFake (options) =>
if options.url is "/correct"
options.success {"data":"yay"}
来源:https://stackoverflow.com/questions/11550926/preventing-ajax-call-with-jasmine-and-sinon-using-backbone