Sinon.js的fakeServer在使用respond方法时没有触发回调函数

4

我正在尝试使用Sinon.js模拟POST请求的服务器响应。它似乎工作正常,但是没有触发成功回调。

# In the Exercise model:

  submit: (query) ->
    callback = (data) -> alert(data)
    $.post(@url(), { query: query }, callback)

# In the Exercise spec:

  beforeEach ->
    @server = sinon.fakeServer.create()
    @server.respondWith('POST', @exercise.url(),
                        [ 200, { "Content-Type": "application/json" },
                        '[{ correct: true, result_set: {} }' ])

    @exercise.submit('select * from students')


  # passes
  it "request is a POST", ->
    expect(@server.requests[0].method).toEqual('POST')

  # passes
  it "submits to the correct url", ->
    expect(@server.requests[0].url).toEqual(@exercise.url())

  it "fires the callback", ->
    @server.respond()
   # no callback fired! but if I inspect the server object I can see that
   # the queue is empty, and the response is properly attached to the request object.
   # see the state below

# State of the Server object

{"requests":[
{"readyState":4,
 "requestHeaders":
    {"Content-Type":"application/x-www-form-urlencoded;charset=utf-8",
     "Accept":"*/*",
     "X-Requested-With":"XMLHttpRequest"},
 "requestBody":"query=select+*+from+students",
 "status":200,
 "statusText":"OK",
 "method":"POST",
 "url":"exercises/some_id",
 "async":true,
 "responseText":"[
    { correct: true,
      result_set: 
        {} }",
 "responseXML":null,
 "sendFlag":true,
 "errorFlag":false,
 "responseHeaders":
    {"Content-Type":"application/json"}}],
 "responses":[
 {"method":"POST",
 "url":"exercises/some_id",
 "response":[200,
    {"Content-Type":"application/json"},"[
    { correct: true,
      result_set: 
        {} }"]}],
  "queue":[]}
1个回答

4

由于您的JSON格式无效,它触发了错误回调:'[{ correct: true, result_set: {} }'。尝试使用http://jsonlint.com/验证您的响应,或使用JSON.stringify,这样您就不需要担心它。


好眼力,Christian!我本来以为在JSON解析错误的情况下会出现错误。谢谢。 - brentvatne
错误会在错误回调函数中冒泡;) Sinon大部分情况下并不试图知道你的响应内容,就像浏览器一样。 - Christian Johansen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接