Sinon.js fakeServer не запускает обратный вызов с методом ответа - PullRequest
4 голосов
/ 20 февраля 2012

Я пытаюсь смоделировать ответ сервера на запрос POST, используя Sinon.js.Кажется, что он работает нормально, за исключением того, что это не вызывает обратный вызов успеха.

# 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 голосов
/ 20 февраля 2012

Он запускает обратный вызов ошибки, потому что ваш JSON недействителен: '[{ correct: true, result_set: {} }' Попробуйте использовать http://jsonlint.com/ для проверки ваших ответов или используйте JSON.stringify, тогда вам не нужно об этом беспокоиться.

...