问题描述
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.
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"}
这篇关于使用 Backbone 防止 Jasmine 和 Sinon 的 AJAX 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!